do.call("rbind", list(data, frames)) 但也通过其原始数据帧对每一行进行索引
do.call("rbind", list(data, frames)) but also index each row by its original data frame
df1 <- data.frame(a = 1:2, b = 3:4)
df2 <- data.frame(a = 5:6, b = 7:8)
# A common method loses the origin of each row.
do.call("rbind", list(df1, df2))
## a b
## 1 1 3
## 2 2 4
## 3 5 7
## 4 6 8
# Whereas here, X1 records which data frame each row originated in.
library(plyr)
adply(list(df1, df2), 1)
## X1 a b
## 1 1 1 3
## 2 1 2 4
## 3 2 5 7
## 4 2 6 8
有没有其他方法可以做到这一点,也许更有效?
这是一种方法。
library(dplyr)
library(tidyr)
foo <- list(df1, df2)
unnest(foo, names) %>%
mutate(names = gsub("^X", "", names))
# names a b
#1 1 1 3
#2 1 2 4
#3 2 5 7
#4 2 6 8
带底座:
df1 <- data.frame(a = 1:2, b = 3:4)
df2 <- data.frame(a = 5:6, b = 7:8)
frames <- list(df1, df2)
do.call(rbind, lapply(seq_along(frames), function(x) {
frames[[x]]$X1 <- x
frames[[x]]
}))
## a b X1
## 1 1 3 1
## 2 2 4 1
## 3 5 7 2
## 4 6 8 2
顺便说一句,如果您想了解 plyr
这对 (plyr::adply)
、(plyr:::splitter_a)
和 (plyr::ldply)
有何影响。与那个答案相比,这些答案微不足道:-)
df1 <- data.frame(a = 1:2, b = 3:4)
df2 <- data.frame(a = 5:6, b = 7:8)
# A common method loses the origin of each row.
do.call("rbind", list(df1, df2))
## a b
## 1 1 3
## 2 2 4
## 3 5 7
## 4 6 8
# Whereas here, X1 records which data frame each row originated in.
library(plyr)
adply(list(df1, df2), 1)
## X1 a b
## 1 1 1 3
## 2 1 2 4
## 3 2 5 7
## 4 2 6 8
有没有其他方法可以做到这一点,也许更有效?
这是一种方法。
library(dplyr)
library(tidyr)
foo <- list(df1, df2)
unnest(foo, names) %>%
mutate(names = gsub("^X", "", names))
# names a b
#1 1 1 3
#2 1 2 4
#3 2 5 7
#4 2 6 8
带底座:
df1 <- data.frame(a = 1:2, b = 3:4)
df2 <- data.frame(a = 5:6, b = 7:8)
frames <- list(df1, df2)
do.call(rbind, lapply(seq_along(frames), function(x) {
frames[[x]]$X1 <- x
frames[[x]]
}))
## a b X1
## 1 1 3 1
## 2 2 4 1
## 3 5 7 2
## 4 6 8 2
顺便说一句,如果您想了解 plyr
这对 (plyr::adply)
、(plyr:::splitter_a)
和 (plyr::ldply)
有何影响。与那个答案相比,这些答案微不足道:-)