使用lapply保存输入列表的名称

时间:2016-06-21 01:41:14

标签: r

我使用lapply在列表列表上执行功能。外部列表中的子列表已命名,我希望能够访问这些内部列表的名称以执行某些条件逻辑。让我来看看下面的尝试:

# dput of my sample data
main_list <- structure(list(sublist1 = structure(list(df1 = structure(list(
    X1 = 0, X2 = 0), .Names = c("X1", "X2"), row.names = c(NA, 
-1L), class = "data.frame"), df2 = structure(list(X1 = 0, X2 = 0), .Names = c("X1", 
"X2"), row.names = c(NA, -1L), class = "data.frame")), .Names = c("df1", 
"df2")), sublist2 = structure(list(df3 = structure(list(X1 = 0, 
    X2 = 0), .Names = c("X1", "X2"), row.names = c(NA, -1L), class = "data.frame"), 
    df4 = structure(list(X1 = 0, X2 = 0), .Names = c("X1", "X2"
    ), row.names = c(NA, -1L), class = "data.frame")), .Names = c("df3", 
"df4"))), .Names = c("sublist1", "sublist2"))

以下是我的名单命名方式

> names(main_list)
[1] "sublist1" "sublist2"
> names(main_list$sublist1)
[1] "df1" "df2"

因此,每个内部列表的名称为sublist1sublist2,然后每个子列表中包含两个数据框。

所需输出(已编辑)

我希望能够访问我的子列表的名称,即在lapply期间使用的函数中的sublist1sublist2。我编辑了我的示例函数,以获得更清晰的期望输出:

> example <- function(input){
+   if(names(input)=="sublist1"){
+     return(1)
+   } else{
+     return(2)
+   }
+ }
> lapply(main_list,example)
$sublist1
[1] 2

$sublist2
[1] 2

Warning messages:
1: In if (names(input) == "sublist1") { :
  the condition has length > 1 and only the first element will be used
2: In if (names(input) == "sublist1") { :
  the condition has length > 1 and only the first element will be used

我想要接收的正确输出是:

> lapply(main_list,example)
$sublist1
[1] 1

$sublist2
[1] 2 

尝试

以下是我失败的一些尝试:

> lapply(main_list,names)
$sublist1
[1] "df1" "df2"

$sublist2
[1] "df3" "df4"

> lapply(main_list,colnames)
$sublist1
NULL

$sublist2
NULL

> test <- function(input){
   print(substitute(input))
 }
> lapply(main_list,test)
X[[i]]
X[[i]]
$sublist1
X[[i]]

$sublist2
X[[i]]

我可以看到$sublist1$sublist2出现在我的尝试中,但我实际上存在问题,然后对这些值进行操作。

0 个答案:

没有答案