我需要有关如何以迭代方式管理列表的帮助。
我有以下列表list
,它由几个具有相同列但行数不同的数据帧组成。例如:
[[1]]
id InpatientDays ERVisits OfficeVisits Narcotics
1 a 0 0 18 1
2 b 1 1 6 1
3 c 0 0 5 3
4 d 0 1 19 0
5 e 8 2 19 3
6 f 2 0 9 2
[[2]]
id InpatientDays ERVisits OfficeVisits Narcotics
7 a 16 1 8 1
8 b 2 0 8 0
9 c 2 1 4 3
10 d 4 2 0 2
11 e 6 5 20 2
12 a 0 0 7 4
我想应用一个函数来获取每个"数据帧的ID的所有可能组合"在列表中。
我打算尝试这样的事情lapply(list1, function(x) combn(unique(list1[x]$id)))
这当然不起作用..希望得到类似的东西:
[[1]]
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15]
[1,] "a" "a" "a" "a" "a" "b" "b" "b" "b" "c" "c" "c" "d" "d" "e"
[2,] "b" "c" "d" "e" "f" "c" "d" "e" "f" "d" "e" "f" "e" "f" "f"
[[2]]
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] "a" "a" "a" "a" "b" "b" "b" "c" "c" "d"
[2,] "b" "c" "d" "e" "c" "d" "e" "d" "e" "e"
这可能吗?我确信这适用于单个数据帧df
combn(unique(df$id),2)
答案 0 :(得分:6)
我们需要使用unique(x$id)
lapply(list1, function(x) combn(unique(x$id),2))
OP的代码使用lapply
循环'list1'。匿名函数调用(function(x)
)返回list
中的每个'data.frame',即'x'是'data.frame'。因此,我们只需要调用x$id
(或x[['id']]
)来提取“id”列。实质上,'x'不是索引。但是,如果我们需要基于索引进行子集化,我们必须循环遍历'list1'的序列(或者如果list
元素被命名,则循环遍历它的names
)
lapply(seq_along(list1), function(i) combn(unique(list1[[i]]$id), 2))