如何将计算序列分配给 r 中的变量序列 [英] how to assign a sequence of computations to a sequence of variables in r
问题描述
我想在循环中遇到一些棘手的挑战,我想在循环中做得更快.如何将一系列小型计算分配给变量序列?示例:
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)
其中ben(i)和mal(i)是序列为1:40的7×13矩阵,而fex(i)也是变量名称为1:40的序列.基本上,我已经将一些数据拆分为不同的折叠,并希望对拆分后的数据集进行组合以执行其他一些计算.我已经使用lapply遍历rbind和其他函数,但是如何在矩阵序列上应用rbind这样的函数并将值也存储在变量序列中来实现此任务呢?
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?
谢谢.
推荐答案
您应该在此处使用列表:
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]]
如果必须具有单独的变量,请使用 assign
:
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
但是,您还应该尝试将它们放在getgo的列表中.
However, you should also try to place them in a list from the getgo.
这篇关于如何将计算序列分配给 r 中的变量序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!