我在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。内容应为x3的x1的第一个数字)和x4的x2的第一个数字。
我知道如何使用单个数据框或简单的嵌套列表来做到这一点:
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]]进行双循环?
答案 0 :(得分: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
}
}
}