提问人:Fadhil Dzikri 提问时间:3/15/2023 最后编辑:Fadhil Dzikri 更新时间:3/15/2023 访问量:37
将行与不同的变量组合在一起
combine the row with the different variable
问:
我想组合 2 个数据帧,但有不同的变量 例
df1=data.frame(x1=c(1,1,1,2,2,2,2),x2=c("a","a","b","b","c","c","c"),x3=c("t","u","v","w","x","y","z"),x4=c("apple","apple","mango","mango","mango","mango","mango"))
df2=data.frame(x1=c(1,1,1,2,2,2,2),x2=c("a","a","b","b","c","c","c"),x4=c("apple","banana","banana","melon","melon","melon","melon"),x5=c("t","u","v","w","x","y","z"))
我尝试过 cbind、rbind、merge、左右连接,但没有人能像我预期的那样。我对 DF 的期望是有 13 行和 5 列。为什么选择13列?因为在第 1 行可以组合
答:
1赞
Maël
3/15/2023
#1
您可以执行以下操作:
full_join(mutate(df1, x6 = x3), mutate(df2, x3 = x5)) %>% select(x1, x2, x3 = x6, x4, x5)
x1 x2 x3 x4 x5
1 1 a t apple t
2 1 a u apple <NA>
3 1 b v mango <NA>
4 2 b w mango <NA>
5 2 c x mango <NA>
6 2 c y mango <NA>
7 2 c z mango <NA>
8 1 a <NA> banana u
9 1 b <NA> banana v
10 2 b <NA> melon w
11 2 c <NA> melon x
12 2 c <NA> melon y
13 2 c <NA> melon z
评论
0赞
Fadhil Dzikri
3/15/2023
谢谢,但是如果我有很多变量,我应该输入所有变量吗?
评论
dplyr::bind_rows(df1, df2)