我有两个如下数据框:
df1 <- data.frame(ID = c(1:4),
Year = 2001,
a_Var1 = c("A","B","C","D"),
a_Var2 = c("T","F","F","T"))
df2 <- data.frame(ID = c(1:4),
Year = 2002,
b_Var1 = c("E","F","G","H"))
所需的最终产品是
df_combined <- data.frame(ID = c(1,1,2,2,3,3,4,4),
Year = c(2001,2002,2001,2002,2001,2002,2001,2002),
Var1 = c("A","E","B","F","C","G","D","H"),
Var2 = c("T",NA,"F",NA,"F",NA,"T",NA))
问题是如何以以下方式“ rbind”:删除前缀a_
或b_
并使Var1
,Var2
等成为新列。 / p>
尝试过plyr
的{{1}},但这不能解决问题。
答案 0 :(得分:3)
这里是一种选择。通过用“ ID”删除包含list
和rename
的前缀部分,将数据集放置在_
,arrange
中
library(tidyverse)
map_df(list(df1, df2), ~ .x %>%
rename_all(~ str_remove(.x, "^[^_]+_"))) %>%
arrange(ID)
# ID Year Var1 Var2
#1 1 2001 A T
#2 1 2002 E <NA>
#3 2 2001 B F
#4 2 2002 F <NA>
#5 3 2001 C F
#6 3 2002 G <NA>
#7 4 2001 D T
#8 4 2002 H <NA>