r - R循环遍历三重嵌套列表
问题描述
我在 R 中有一个三重嵌套列表。结构就像下面的测试列表:
df_yes = data.frame(replicate(2,sample(0:130,30,rep=TRUE)))
df_no = data.frame(replicate(2,sample(0:130,20,rep=TRUE)))
s1 = list(df_yes, df_no)
names(s1) = c("yes", "no")
df_yes = data.frame(replicate(2,sample(0:130,25,rep=TRUE)))
df_no = data.frame(replicate(2,sample(0:130,15,rep=TRUE)))
s2 = list(df_yes, df_no)
names(s2) = c("yes", "no")
DJF = list(s1, s2)
names(DJF) = c("s1", "s2")
df_yes = data.frame(replicate(2,sample(0:130,60,rep=TRUE)))
df_no = data.frame(replicate(2,sample(0:130,10,rep=TRUE)))
s1 = list(df_yes, df_no)
names(s1) = c("yes", "no")
df_yes = data.frame(replicate(2,sample(0:530,25,rep=TRUE)))
df_no = data.frame(replicate(2,sample(0:230,15,rep=TRUE)))
s2 = list(df_yes, df_no)
names(s2) = c("yes", "no")
JJA = list(s1, s2)
names(JJA) = c("s1", "s2")
total_list = list(DJF, JJA)
names(total_list) = c("DJF", "JJA")
我现在想在 yes 和 no 数据框中添加 $x3 和 $x4 。内容应该是x1的第一个数字x3)和x2的第一个数字x4。
我知道如何使用单个数据框或简单的嵌套列表来做到这一点:
df1 = total_list$DJF$s1$yes
df1$x3 = substr(df1$X1, 1,1)
df1$x4 = substr(df1$X2, 1,1)
或者在普通列表中使用循环:
for(i in 1:length(df)){
df[[i]]$v3 = substr(df[[i]][,1], 1,1)}
但是如何使用循环访问三重嵌套列表?我是否必须使用 2 个变量创建一个双循环,例如 [[i]][[k]][[1]]?
解决方案
这不是最合适的解决方案,希望这会奏效
N <- names(total_list)
for (i in 1:length(N)) {
name1 <- N[i]
product1 = total_list[[name1]]
K <- names(product1)
for (n in 1:length(K)) {
name2 <- K[n]
product2 = product1[[n]]
dfnames = names(product2)
for (l in dfnames) {
df_t = product2[[l]]
df_t$x3 = substr(df_t$X1, 1,1)
df_t$x4 = substr(df_t$X2, 1,1)
df_t$x3 <- as.numeric(df_t$x3)
df_t$x4 <- as.numeric(df_t$x4)
total_list[[name1]][[name2]][[l]] <- df_t
}
}
}
推荐阅读
- sql - 从 SQL 获取数据 - 在 IntelliJ 中生成代码
- blazor - Blazor WASM - 错误:无法启动平台 - 部署后有时会显示一次错误
- twilio - 您尝试向您帐户上未启用的电话号码发起外拨电话
- .net - 从 Settings.settings 生成的 *.config 部分不遵守 Visual Studio XML 设置
- java - Quarkus Hibernate 找不到所需类型 [interface javax.transaction.TransactionManager] 和限定符 [[]] 的 bean
- jenkins - jenkins 下的命令“pod repo push”(使用 bigsur macstadium 节点)产生“No such file or directory xxxxxxxxxxxx REPO_NAME.podspec.json”
- swift - SwiftUI 和 db 使用 Core Data 为空
- javascript - Cheerio 不是服务器上与本地具有相同 node.js 版本的功能
- postgresql - 无法持久更改 search_path
- c# - 软删除数据但在获取时出现问题 | EF 核心,C#