r - 如何为 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]]
部分。
解决方案
我将通过使用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
语句中。
推荐阅读
- c++ - 如何设置 char [ ] 以便在我们输入任何字符或不输入任何字符时都会给出输出。代码如下
- reactjs - 反应谷歌地图没有在指定的纬度,经度上打开,而是在随机的地方
- javascript - 当我要在 js 中创建一个机器人并且我无法修复它时,会发生此错误。有人能帮我吗?
- javascript - AWS Lambda 上的 FabricJS 节点 - 字体未出现在数据 uri 图像上
- arrays - 无法找到二和问题的正确输出
- html - 如何在嵌入 html 的右侧预填充 youtube 播放列表视频
- outlook - Outlook VSTO - 创建邮件并将其保存在收件箱中 - 使用 Outlook Redemption 设置发件人
- python - 如何在不丢失迄今为止获得的数据的情况下停止 Jupyter Notebook 循环
- kotlin - 并发修改如何与协程一起工作?
- azure-devops - 依赖项更改时在 Azure DevOps 中更新单击一次应用程序