我有这些数据:
dat=list(structure(list(Group.1 = structure(3:4, .Label = c("A","B", "C", "D", "E", "F"), class = "factor"), Pr1 = c(65, 75)), row.names = c(NA, -2L), class = "data.frame"),NULL, structure(list( Group.1 = structure(3:4, .Label = c("A","B", "C", "D", "E", "F"), class = "factor"), Pr1 = c(81,4)), row.names = c(NA,-2L), class = "data.frame"))
Run Code Online (Sandbox Code Playgroud)
我想使用组合使用 bind_rows(dat)
但保持索引号作为可变输出包含Type([[1]] and [[3]])
type Group.1 Pr1
1 1 C 65
2 1 D 75
3 3 C 81
4 3 D 4
Run Code Online (Sandbox Code Playgroud)
data.table解决方案
使用rbindlist(),它具有内置的id-support,支持NULL df.
library(data.table)
rbindlist( dat, idcol = TRUE )
.id Group.1 Pr1
1: 1 C 65
2: 1 D 75
3: 3 C 81
4: 3 D 4
Run Code Online (Sandbox Code Playgroud)
dplyr - 部分解决方案
bind_rows也有ID支持,但它'跳过'空元素......
bind_rows( dat, .id = "id" )
id Group.1 Pr1
1 1 C 65
2 1 D 75
3 2 C 81
4 2 D 4
Run Code Online (Sandbox Code Playgroud)
请注意,来自dat的第三个元素的ID变为2,而不是3.
根据您的文档,bind_rows()
您可以提供.id
函数参数的名称。当你申请bind_rows()
到的名单data.frame
小号包含您的列表的名称data.frame
s的分配给标识列。[编辑] 但是@Wimpel 提到了一个问题:
names(dat)
NULL
Run Code Online (Sandbox Code Playgroud)
但是,将名称提供给列表将执行以下操作:
names(dat) <- 1:length(dat)
names(dat)
[1] "1" "2" "3"
bind_rows(dat, .id = "type")
type Group.1 Pr1
1 1 C 65
2 1 D 75
3 3 C 81
4 3 D 4
Run Code Online (Sandbox Code Playgroud)
或者在一行中,如果您愿意:
bind_rows(setNames(dat, seq_along(dat)), .id = "type")
Run Code Online (Sandbox Code Playgroud)