【问题标题】:Sub-setting a data frame into multiple other dataframes using a loop使用循环将数据帧子设置为多个其他数据帧
【发布时间】:2020-04-15 00:45:09
【问题描述】:

我有以下名为 stationDF 的数据框。 https://i.stack.imgur.com/Ucph0.png

我还有向量 from_nodesto_nodesfrom_nodes <- c(1, 156, 153, 3)to_nodes <- c(156, 153, 3, 185)。正如您在数据框中看到的,这些 from 和 to 向量对应于我的 stationDF 中的“from”和“to”列。我正在尝试根据这些向量对这个 stationDF 进行子集化。我试过了:

x1 <- stationDF[stationDF$from == from_nodes[1] & stationDF$to == to_nodes[1] |
                stationDF$from == to_nodes[1] & stationDF$to == from_nodes[1],]

这是从 1 到 156 或 156 到 1 的所有站的子设置我的数据框。以下是此的输出:https://i.stack.imgur.com/TLqv4.png

我想对 from 和 to 向量中的其余变量执行此操作,但不是硬编码。例如,

for (i in 1:length(from){
    x <- stationDF[stationDF$from == from_nodes[i] & stationDF$to == to_nodes[i] |
                   stationDF$from == to_nodes[i] & stationDF$to == from_nodes[i],]
}

这显然不会像这样工作,因为它会覆盖以前的迭代,但这是思考过程。我想最终得到四个不同的 stationDF 子集,或者如果四个不能完成,甚至只有一个大的子集。有什么帮助,谢谢。

【问题讨论】:

标签: r for-loop subset


【解决方案1】:

您可以轻松地对您的代码进行简单修改,如下所示:

x_ls <- list()
for (i in 1:length(from_nodes){
  x_ls[[i]] <- stationDF[stationDF$from == from_nodes[i] & stationDF$to == to_nodes[i] |
                         stationDF$from == to_nodes[i] & stationDF$to == from_nodes[i],]
}
x <- do.call('rbind', x_ls)

这将获取循环输出的每个数据帧并将其保存到列表中。最后,您只需使用rbind 调用的do.call 函数将列表中的所有数据帧绑定在一起。

"do.call" 只是一个函数,它允许您将值作为参数解压缩到另一个函数中。在这种情况下,它将与 rbind(x_ls[[1]], x_ls[[2]], x_ls[[3]], x_ls[[4]]) 同义。

【讨论】:

    猜你喜欢
    • 2023-01-19
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2019-07-29
    • 2013-11-21
    相关资源
    最近更新 更多