I was trying to learn R using a book. I was trying to do an example where for each row of the matrix, the corresponding element of the vector will be either 1 or 0, depending on whether the majority of the
first d elements in that row is 1 or 0. The code used was:-
copymaj <- function(rw,d) {
maj <- sum(rw[1:d]) / d
return(if(maj > 0.5) 1 else 0)
}
x
[,1] [,2] [,3] [,4] [,5]
[1,] 1 0 1 1 0
[2,] 1 1 1 1 0
[3,] 1 0 0 1 1
[4,] 0 1 1 1 0
apply(x,1,copymaj,3)
It is showing the above error. Also if I do apply(x,1,copymaj(3)), still error is shown.
R 2.13 is installed
Please help!
As @BenBarnes pointed out, you probably misspelled
sum, I think you wrotesiminstead ofsum.I was able to reproduce your error by doing:
I really think you misspelled
sum.apply(x,1,copymaj1(3))won’t work becase if you read?applyyou’ll seeapply(X, MARGIN, FUN, ...), thenapply(x,1,copymaj1(3))wil produce an error because...replaces the arguments toFUN(d=3in your case) is missed. In order to pass optional arguments to your fun you have to use...as inapply(x,1,copymaj1,3)but not usingapply(x,1,copymaj1(3)).