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

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

5 Comments

I was just typing this answer :)
Thanks. I will definately have a look at these tutorials. Best
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 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().
Hi Joris, sorry for my late answer to say thank you. I'll keep in mind your advice
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 } 

1 Comment

@user1021000 in fact you have problem with definition of "holder", it should be matrix not vector.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.