Noah Silverman <noah <at> smartmediacorp.com> writes: > > Hi, > > Is there a way to build up a vector, item by item. In perl, we can > "push" an item onto an array. How can we can do this in R? > I have a loop that generates values as it goes. I want to end up with a > vector of all the loop results. > > In perl it woud be: > > for(item in list){ > result <- 2*item^2 (Or whatever formula, this is just a pseudo example) > Push(@result_list, result) (This is the step I can't do in R) > } >
Just do add an item at the end. Example: > mydat <- 1 > mydat[2] <- 33 > mydat[3] <- -4 > mydat[4] <- 12 > mydat[length(mydat)+1] <- 22 > mydat [1] 1 33 -4 12 22 > mydat[length(mydat)+1] <- 5623 > mydat [1] 1 33 -4 12 22 5623 > mydat[length(mydat)+1] <- 0.8962 > mydat [1] 1.0000 33.0000 -4.0000 12.0000 22.0000 5623.0000 0.8962 When doing it in a loop, don't use length() over and over, just count up the index. For many entries, it would be faster, if you just allocate the array that should be written, by just writing 0 into it, or empty strings or something like this... > mydat[1:100] <- 0 > mydat [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 [38] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 [75] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 > mydat <- 1 > mydat[2] <- 33 > mydat[3] <- -4 > mydat [1] 1 33 -4 instead of "mydat[1:100] <- 0" use the length of the itemlist as second parameter. Ciao, Oliver ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.