【发布时间】:2021-11-17 20:10:28
【问题描述】:
我想仅在 df1 中 col2 的值为 NA 的情况下将一个 tibble (df2) 加入 (left_join) 到另一个 (df1)。我目前使用的代码不是很优雅。任何关于如何缩短代码的建议将不胜感激!
library(tidyverse)
# df1 contains NAs that need to be replaced by values from df2, for relevant col1 values
df1 <- tibble(col1 = c("a", "b", "c", "d"), col2 = c(1, 2, NA, NA), col3 = c(10, 20, 30, 40))
df2 <- tibble(col1 = c("a", "b", "c", "d"), col2 = c(5, 6, 7, 8), col3 = c(50, 60, 70, 80))
# my current approach
df3 <- df1 %>%
filter(!is.na(col2))
df4 <- df1 %>%
filter(is.na(col2)) %>%
select(col1)%>%
left_join(df2)
# output tibble that is expected
df_final <- df3 %>%
bind_rows(df4)
【问题讨论】:
-
有什么理由要
join而不是bind_rows()和过滤器? -
@akash87 我认为因为
col2的值在df1和df2中是不同的,所以如果你绑定行并过滤你最终会得到df2的值,这似乎不受欢迎。