3

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

Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
user1021000
  • 237
  • 1
  • 3
  • 8

2 Answers2

3

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?

Community
  • 1
  • 1
Joris Meys
  • 106,551
  • 31
  • 221
  • 263
  • I was just typing this answer :) – Paul Hiemstra Dec 12 '11 at 13:53
  • Thanks. I will definately have a look at these tutorials. Best – user1021000 Dec 12 '11 at 13:59
  • 1
    Hi, just a comment. I always get stuck trying to extract the for loop outputs. I have reviewed several R tutorials and books and always the examples are very basic. Actually, the logic behind a for loop is simple, but things get complicated depending on the function that is being repeated. Thus, outputs may be vectors, lists, etc, and get them has been a nightmare for me. – Rafael Nov 10 '14 at 11:22
  • @Rafael If the output of the function is unknown or different each time it goes through the loop, using lists is the safest. But in most cases, you can solve all that by using sapply() or lapply(). – Joris Meys Nov 11 '14 at 13:43
  • Hi Joris, sorry for my late answer to say thank you. I'll keep in mind your advice – Rafael Mar 24 '15 at 06:38
2

You should make a matrix of the correct dimesions and then fill with the values. Also remember to place a comma after the i, so you index the matrix correctly.

holder<-matrix(nrow = 3, ncol = 3)

for(i in 1:3)

{

  apple<-c(i+1, i*2, i^3)

  holder[i,]<-apple

}
Luciano Selzer
  • 9,806
  • 3
  • 42
  • 40