我有一个这样的数据框:
df = data.frame(id = c(1,1,3,4,4), stockoprice1 = c(3,4,2,45,1))
还有第二个这样的
df2 = data.frame(id = c(1,4), name = c("price1","price2"))
我想将它们合并以便获得如下结果:
> dfexpected = data.frame(id = c(1,1,3,4,4), stockprice1 = c(3,4,2,45,1), name = c("price1","price1",NA,"price2","price2"))
> dfexpected
id stockprice1 name
1 1 3 price1
2 1 4 price1
3 3 2 <NA>
4 4 45 price2
5 4 1 price2
哪个是合适的合并选项?
答案 0 :(得分:1)
df = data.frame(id = c(1,1,3,4,4), stockoprice1 = c(3,4,2,45,1))
df2 = data.frame(id = c(1,4), name = c("price1","price2"))
dfexpected <- dplyr::left_join(df, df2)
dfexpected
#> Joining, by = "id"
#> id stockoprice1 name
#> 1 1 3 price1
#> 2 1 4 price1
#> 3 3 2 <NA>
#> 4 4 45 price2
#> 5 4 1 price2
由reprex package(v0.2.0)于2019-02-10创建。
答案 1 :(得分:1)
您可以在使用merge
的同时使用基本tidyverse
:
df %>%
merge(df2, by = "id", all = TRUE)
id stockoprice1 name
1 1 3 price1
2 1 4 price1
3 3 2 <NA>
4 4 45 price2
5 4 1 price2
我喜欢管道选项,但是通过设置merge
,all
或all.x
中的选项,基础all.y
对于各种类型的联接确实非常灵活。尝试获得预期的输出很容易。