简体   繁体   中英

looping through a list of vectors in r

i am trying to loop through a list a vectors and assign values on the way: I generate 10 vectors like this:

for(i in 1:10){
  vecname <- paste('blub',i,sep='')
  assign(vecname,vector(mode='numeric',length = my_len))
} 

ls() = blub1, blub2 .... blub10

now i have another vector bla <- 100:109

what i basically want to do is

blub1[1] <- bla[1]
blub2[1] <- bla[2]
blub3[1] <- bla[3]
...
blub10[1] <- bla[10]

I am pretty sure there is an more elegant solution to his problem. Help would be very much appreciated.

Thanks and have a nice day!

Here is how I would do it, following the "R way" of "lists, not for loops":

my_len <- 3
blub <- replicate(10, vector(mode = "numeric", length = my_len), simplify = FALSE)
bla <- 100:109
blub <- Map(function(a, b) {
  a[1] <- b
  a
}, blub, bla)
# [[1]]
# [1] 100   0   0
# 
# [[2]]
# [1] 101   0   0
# 
# [[3]]
# [1] 102   0   0
# 
# [[4]]
# [1] 103   0   0
# 
# [[5]]
# [1] 104   0   0
# 
# [[6]]
# [1] 105   0   0
# 
# [[7]]
# [1] 106   0   0
# 
# [[8]]
# [1] 107   0   0
# 
# [[9]]
# [1] 108   0   0
# 
# [[10]]
# [1] 109   0   0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM