首页 > 解决方案 > 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]]?

标签: rlistloopsdataframenested

解决方案


这不是最合适的解决方案,希望这会奏效

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
    }

  }

}

推荐阅读