使自定义函数处理嵌套列表

Make custom function handle nested lists

可重现的示例:2 个嵌套列表,定义如下,具有各自的列名

包含 2 个具有 [2,3] 和 [3,5] 维度的 df 的嵌套列表 1

list1 <- list(as.data.frame(matrix(nrow = 2, ncol = 3)), as.data.frame(matrix(nrow = 3, ncol = 5)))
colnames(list1[[1]]) <- c("M1", "M2", "M3")
colnames(list1[[2]]) <- c("X1", "X2", "X3", "X4", "X5")
list1

包含 2 个具有 [3,4] 和 [2,5] 维度的 df 的嵌套列表 2

list2 <- list(as.data.frame(matrix(nrow = 3, ncol = 4)), as.data.frame(matrix(nrow = 2, ncol = 5)))
colnames(list2[[1]]) <- c("L1", "L2", "L3", "L4")
colnames(list2[[2]]) <- c("Z1", "Z2", "Z3", "Z4", "Z5")
list2

采用每个 df 的同名并生成字符串的自定义函数(例如“F1 =~ M1 + M2 + M3”)

foo_gen_CFA_syn = function(data){ # arg: data = individual list with nested dataframes  
    
    syntax_of_X_CFA_models <- vector(mode = "character", length = length(data))

    for(i in 1:length(data)){
        syntax_of_X_CFA_models[i] <- paste0("F", sep = "", i, sep = " =~ ", paste(colnames(data[[i]]), collapse = " + "))
    }
    
    return(syntax_of_X_CFA_models)
}

这对列表 1 和列表 2 单独有效并产生以下输出

> foo_gen_CFA_syn(data = list1)
[1] "F1 =~ M1 + M2 + M3"           "F2 =~ X1 + X2 + X3 + X4 + X5"
> foo_gen_CFA_syn(data = list2)
[1] "F1 =~ L1 + L2 + L3 + L4"      "F2 =~ Z1 + Z2 + Z3 + Z4 + Z5"

列表 1 和列表 2 一起使用也能正常工作

foo_gen_CFA_syn(data = c(list1, list2))
    [1] "F1 =~ M1 + M2 + M3"           "F2 =~ X1 + X2 + X3 + X4 + X5" "F3 =~ L1 + L2 + L3 + L4"     
    [4] "F4 =~ Z1 + Z2 + Z3 + Z4 + Z5"

问题:我不想提供列表向量,而是想指定一个包含所有列表的嵌套列表。像下面的东西

list3 <- list(list1, list2)

但这就是它中断并产生错误输出的地方

> foo_gen_CFA_syn(data = list3)
[1] "F1 =~ " "F2 =~ "

在函数中添加unlist(data, recursive = FALSE)

foo_gen_CFA_syn = function(data){ # arg: data = individual list with nested dataframes  
 
  data <- unlist(data, recursive = FALSE)
   
  syntax_of_X_CFA_models <- vector(mode = "character", length = length(data))
  for(i in 1:length(data)){
    syntax_of_X_CFA_models[i] <- paste0("F", sep = "", i, sep = " =~ ", paste(colnames(data[[i]]), collapse = " + "))
  }
  
  return(syntax_of_X_CFA_models)
}

输出:

foo_gen_CFA_syn(list3)
#"F1 =~ M1 + M2 + M3"           "F2 =~ X1 + X2 + X3 + X4 + X5" "F3 =~ L1 + L2 + L3 + L4"      "F4 =~ Z1 + Z2 + Z3 + Z4 + Z5"