Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
96 views
in Technique[技术] by (71.8m points)

r - How to loop over multiple objects

In the recent past I faced a similar problem oftentimes. To make it super easy to reproduce, here is some sample data for a very basic example:

# create five random matrices with the same dimensions
for (i in 1:5) {
  assign(paste0("mat", i), matrix(rexp(200), 10,10))
}

# create five empty vectors with the same length
for (i in 1:5) {
  assign(paste0("vec", i), vector(mode= "numeric", length= 10))
}

# fill vec1 with the colsums of mat1
for (i in 1:10) {
  vec1[i] <- colSums(mat1)[i]
}

# fill each vector with the colsums of each corresponding matrix -> this FAILS
for (i in 1:5) {
  for (j in 1:10) {
    get(paste0("vec", i))[j] <- colSums(get(paste0("mat", i)))[j]
  }
}

What I am looking for is a way to fill the single vectors with the colsums of the corresponding matrices. You can see in the code above that this is done super easily for one vector with one corresponding matrix. But when it comes to multiple objects the loop fails since it does not accept the get command at the beginning.

Anybody here with an elegant solution for that?

question from:https://stackoverflow.com/questions/65951673/how-to-loop-over-multiple-objects

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We can use lapply after getting all the matrices in a list and get colSums

result <- lapply(mget(paste0('mat', 1:5)), colSums)
result

#$mat1
# [1]  4.40  8.07  5.78  8.72  5.82  8.47 11.06  6.41  9.85 14.91

#$mat2
# [1]  8.37 10.69 10.55  8.72 15.85  6.01 10.51  8.82 17.36  7.04

#$mat3
# [1] 13.64  6.71 11.60 13.82 10.78  6.49 10.41  6.05  3.93 10.57

#$mat4
# [1]  8.01 10.85  8.96 11.57  7.90 10.33  5.64  9.98  7.84  5.91

#$mat5
# [1] 15.03  6.55 10.54  6.14 12.57 11.70  9.55 11.05  9.36  6.89

To change the above list output to separate vectors as vec1, vec2 etc we can use :

names(result) <- paste0('vec', seq_along(result))
list2env(result, .GlobalEnv)

vec1
#[1]  4.40  8.07  5.78  8.72  5.82  8.47 11.06  6.41  9.85 14.91
vec2
#[1]  8.37 10.69 10.55  8.72 15.85  6.01 10.51  8.82 17.36  7.04

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...