首页 > 解决方案 > 如何为 R 中的每个唯一组合分别保存嵌套循环的结果

问题描述

如何保存嵌套循环的结果并单独保存到我的列表中?

我的data长相是这样的:

> data
  id factor
1  1      A
2  2      B
3  1      A

然后我制作了一个包含 4 个列表的空向量,因为有 2 个唯一值id和 2 个factor

data <- data.frame("id" = c(1, 2, 1), "factor" = c("A", "B", "A"))

empty <- vector(mode = "list", length = 4)
for(i in seq_along(unique(data$id))){
  for (j in seq_along(unique(data$factor))) {
    empty[[i*j]] <- data %>%
      filter(id == unique(id)[i] & factor == unique(factor)[j])
  }
}
empty[[1]]

> empty[[1]]
  id factor
1  1      A
2  1      A

> empty[[2]]
[1] id     factor
<0 rows> (or 0-length row.names)

empty[[1]]有效,但 from empty[[2]]toempty[[3]]给了我一个空列表。我想我搞砸了这个empty[[i*j]]部分。

标签: rdataframenested-loops

解决方案


我将通过使用expand.grid创建一个包含变量的所有唯一组合的数据框,然后在表示该数据框中的行的序列data上运行一个更简单的循环来做到这一点。for所以:

combos <- with(data, expand.grid(id = unique(id), factor = unique(factor)))

empty <- vector(mode = "list", length = nrow(combos))

for (i in seq(nrow(combos))) {

  empty[[i]] <- filter(data, id == combos$id[i] & factor == combos$factor[i])

}

这产生了这个列表:

> empty
[[1]]
  id factor
1  1      A
2  1      A

[[2]]
[1] id     factor
<0 rows> (or 0-length row.names)

[[3]]
[1] id     factor
<0 rows> (or 0-length row.names)

[[4]]
  id factor
1  2      B

如果要将空集的槽保留为NULL,可以将过滤步骤放在if语句中。


推荐阅读