Search code examples
rapplylapplysapplymapply

how to use apply functions familly on vector or matrix index


Is there a way to use the X function to write to a matrix or vector using specific indexes or simply handle an index?

ex.

myVec <- numeric(10)
apply(1:9, 1, function(i,a){ if(i%%2!=0) myVec[i] <-log(a)^i else myVec[i+1] <- a^i},3)


Solution

  • Both the below answers should work. The error you are getting is because apply() takes a matrix and applies the function across the margin (=1 implies by row). So I created a 9 x 1 matrix based on your code.

        apply(matrix(1:9,nrow=9,ncol=1), 1, function(i,a){ if(i%%2!=0) myVec[i] <-log(a)^i else myVec[i+1] <- a^i},3)
    [1]    1.098612    9.000000    1.325969   81.000000    1.600377  729.000000    1.931573 6561.000000    2.331310
        sapply(1:9, function(i,a){ if(i%%2!=0) myVec[i] <-log(a)^i else myVec[i+1] <- a^i},3)
    [1]    1.098612    9.000000    1.325969   81.000000    1.600377  729.000000    1.931573 6561.000000    2.331310