how to assign a sequence of computations to a sequ

2019-08-23 04:46发布

I have a bit tricky challenge in looping which I would want to do in r to make things faster. How do I assign a sequence of small computations to a sequence of variables? Example:

fex1 = rbind(ben1,mal1)
fex2 = rbind(ben2,mal2)
fex3 = rbind(ben3,mal3)
....
....
fex40 = rbind(ben40,mal40)

where ben(i) and mal(i) are 7 by 13 matrix of sequence 1:40 and fex(i) is also a sequence of variable names 1:40. Basically, I have split some data into various folds and would like to rbind a combination of the split datasets to perform some other computation. I have used lapply to loop over rbind and other functions but how do I achieve this task applying a function like rbind over a sequence of matrices and storing the values also in a sequence of variables?

Thanks.

标签: r loops sequence
1条回答
一纸荒年 Trace。
2楼-- · 2019-08-23 05:27

You should really use a list here:

# 
ben <- <list of all your ben's>
mal <- <list of all your mal's>

fex <- mapply(rbind, ben, mal)

# then just index using
fex[[i]]

If you must have separate variables, use assign:

N <- 30 # however many of each `ben` and `mal` you have
for (i in N) {
  bi <- paste0(ben, i)
  mi <- paste0(mal, i)
  fi <- paste0(fex, i)

  assign(fi, rbind(get(bi), get(mi)))
}

NOTE to collect your objects into a list:

ben <- lapply(do.call(paste0, list("ben", 1:N)), get)
mal <- lapply(do.call(paste0, list("mal", 1:N)), get)

# Which can then be indexed by
ben[[7]]
mal[[12]]  # etc

However, you should also try to place them in a list from the getgo.

查看更多
登录 后发表回答