[R] create list of vectors in for loop

Paul Sanfilippo prseye at gmail.com
Tue Dec 6 11:21:52 CET 2016


Thank you Jim.



On 6 December 2016 at 9:17:21 pm, Jim Lemon (drjimlemon at gmail.com) wrote:

Hi Paul,  
The easy to understand way is:  

n <- c(1:10)  
# Create empty list to store vectors  
list_of_vecs <- list()  

# Create n vectors of random numbers - length 10. This works ok.  
for (i in n){  
list_of_vecs[[i]]<-rnorm(10,0,1)  
}  

If you really want to use "assign":  
for (i in n){  
vecname<-paste('vec_', i, sep = '')  
assign(vecname, rnorm(10,0,1))  
list_of_vecs[[i]]<-get(vecname)  
}  

Jim  



On Tue, Dec 6, 2016 at 8:44 PM, Paul Sanfilippo <prseye at gmail.com> wrote:  
> Hi,  
>  
> As an exercise, I am trying to create a list of 10 random number vectors in a loop. I can create the vectors but am unsure how to assemble them in the list as part of the loop. Any advice?  
>  
>  
> # Number of vectors to create  
> n <- c(1:10)  
>  
> # Create empty list to store vectors  
> list_of_vecs <- list()  
>  
> # Create n vectors of random numbers - length 10. This works ok.  
> for (i in seq_along(n)){  
> assign(paste('vec_', i, sep = ''), rnorm(10,0,1))  
> }  
>  
> # But how do I append them in a list. This doesn’t work:  
> for (i in seq_along(n)){  
> list_of_vecs <- list(list_of_vecs,(assign(paste('vec_', i, sep = ''), rnorm(10,0,1))))  
> }  
>  
>  
> Thank you,  
>  
> Paul  
>  
>  
>  
> [[alternative HTML version deleted]]  
>  
> ______________________________________________  
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see  
> 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.  

	[[alternative HTML version deleted]]



More information about the R-help mailing list