如何将 id 列添加到 data.frames 的列表中
How to add an id colum to a list of data.frames
我正在 rbind
将 data.frames 的列表 (k
) 转换为单个 data.frame (current_output
)。
但我想知道如何将 id
列添加到我的结果 data.frame 以便我在 BASE R 中得到我的 desred_output
?
k = list(A = data.frame(d = 1, n = 2), B = data.frame(d = 1:2, n = 2:3))
current_output = do.call(rbind, k)
# d n
#A 1 2
#B.1 1 2
#B.2 2 3
desired_ouput1 = data.frame(id = c(1,2,2), d = c(1,1:2), n = c(2,2:3))
# id d n
#1 1 1 2
#2 2 1 2
#3 2 2 3
desired_ouput2 = data.frame(id = c(A,B,B), d = c(1,1:2), n = c(2,2:3))
# id d n
#1 A 1 2
#2 B 1 2
#3 B 2 3
如果您想要基本的 R 解决方案,下面的代码可能会对您有所帮助
do.call(
rbind,
c(Map(cbind, id = names(k), k),
make.row.names = FALSE
)
)
这给出了
id d n
1 A 1 2
2 B 1 2
3 B 2 3
或者你也可以
cbind(
id = rep(
names(k),
sapply(k, nrow)
),
do.call(rbind, k)
)
这给出了
id d n
A A 1 2
B.1 B 1 2
B.2 B 2 3
我正在 rbind
将 data.frames 的列表 (k
) 转换为单个 data.frame (current_output
)。
但我想知道如何将 id
列添加到我的结果 data.frame 以便我在 BASE R 中得到我的 desred_output
?
k = list(A = data.frame(d = 1, n = 2), B = data.frame(d = 1:2, n = 2:3))
current_output = do.call(rbind, k)
# d n
#A 1 2
#B.1 1 2
#B.2 2 3
desired_ouput1 = data.frame(id = c(1,2,2), d = c(1,1:2), n = c(2,2:3))
# id d n
#1 1 1 2
#2 2 1 2
#3 2 2 3
desired_ouput2 = data.frame(id = c(A,B,B), d = c(1,1:2), n = c(2,2:3))
# id d n
#1 A 1 2
#2 B 1 2
#3 B 2 3
如果您想要基本的 R 解决方案,下面的代码可能会对您有所帮助
do.call(
rbind,
c(Map(cbind, id = names(k), k),
make.row.names = FALSE
)
)
这给出了
id d n
1 A 1 2
2 B 1 2
3 B 2 3
或者你也可以
cbind(
id = rep(
names(k),
sapply(k, nrow)
),
do.call(rbind, k)
)
这给出了
id d n
A A 1 2
B.1 B 1 2
B.2 B 2 3