R For Loop unable to store the data

for-looploopsrstorage

This is probably quite a simple problem, but Im quite new to R. I have a for loop,

holder<-rep(0,3)
for(i in 1:3) {
  apple<-c(i+1, i*2, i^3)
  holder[i]<-apple
}

I get the warning message:

Warning messages:
1: In holder[i] <- apple :
  number of items to replace is not a multiple of replacement length
2: In holder[i] <- apple :
  number of items to replace is not a multiple of replacement length
3: In holder[i] <- apple :
 number of items to replace is not a multiple of replacement length

So what I tried to do is set holder as a matrix, instead of a vector. But I am unable to complete it. Any suggestions would be greatly appreciated.

Best,

James

Best Answer

either you work with it as a matrix :

holder<-matrix(0,nrow=3,ncol=3)
for(i in 1:3){
    apple<-c(i+1, i*2, i^3)
    holder[,i]<-apple  # columnwise, that's how sapply does it too
}

Or you use lists:

holder <- vector('list',3)
for(i in 1:3){
    apple<-c(i+1, i*2, i^3)
    holder[[i]]<-apple
}

Or you just do it the R way :

holder <- sapply(1:3,function(i) c(i+1, i*2,i^3))
holder.list <- sapply(1:3,function(i) c(i+1, i*2,i^3),simplify=FALSE)

On a sidenote : if you struggle with this very basic problem in R, I strongly recommend you to browse through any of the introductions you find on the web. You get a list of them at :

Where can I find useful R tutorials with various implementations?