【问题标题】:how to assign a sequence of computations to a sequence of variables in r如何将计算序列分配给r中的变量序列
【发布时间】:2013-10-03 13:00:07
【问题描述】:

我在循环中遇到了一些棘手的挑战,我想在 r 中做这件事以使事情变得更快。 如何将一系列小计算分配给一系列变量?示例:

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

其中 ben(i) 和 mal(i) 是 1:40 序列的 7 x 13 矩阵,fex(i) 也是 1:40 变量名序列。基本上,我已将一些数据拆分为不同的折叠,并希望 rbind 拆分数据集的组合以执行其他一些计算。我已经使用 lapply 来循环 rbind 和其他函数,但是如何在一系列矩阵上应用像 rbind 这样的函数并将值也存储在一系列变量中来完成这项任务?

谢谢。

【问题讨论】:

  • 你为什么希望它们作为单独的对象开始?如果您能够使用lapply 并将它们放入list,那还不够吗?

标签: r loops sequence


【解决方案1】:

你真的应该在这里使用一个列表:

# 
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:

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)))
}

将您的对象收集到列表中的注意事项:

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 的列表中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-02
    • 1970-01-01
    • 2013-12-17
    • 2017-01-11
    • 2022-01-22
    • 2021-02-12
    • 1970-01-01
    相关资源
    最近更新 更多