使用left_join合并两个带有NA的列的R数据框

5
我的问题是:假设我有一个包含以下列的现有数据框:UID、foo、result。结果已经部分填充。现在,第二个模型预测出额外的行,生成一个包含 UID 和 result 列的第二个数据框:(可在底部找到复制代码)
## df_main
##    UID   foo result
##  <dbl> <chr>  <chr>
## 1     1   moo    Cow
## 2     2   rum   <NA>
## 3     3  oink   <NA>
## 4     4  woof    Dog
## 5     5  hiss   <NA>

## new_prediction
##    UID result
##  <dbl>  <chr>
## 1     3    Pig
## 2     5  Snake

我现在想通过 UID 进行左连接,以得到以下结果列:
## Cow
## <NA>
## Pig
## Dog
## Snake

但是我无法让它工作,因为left_join(df_main, new_prediction, by="UID")创建了result.xresult.y。有没有使用dplyr的方法,或者另一个好的连接列的步骤?我查看了各种函数,但最终决定手动循环所有行。我非常确定有一种更“R”的方法来做到这一点?
数据帧代码:
df_main <- tibble(UID = c(1,2,3,4,5), foo=c("moo", "rum", "oink", "woof", "hiss"), result=c("Cow", NA, NA, "Dog", NA))
new_prediction <- tibble(UID = c(3,5), result = c("Pig", "Snake"))

你可以在这些列上使用 dplyr 中的 coalesce 函数。 - Jake Kaupp
你知道为什么R会表现出这种方式吗?为什么它会创建.x和.y文件? - undefined
2个回答

6

coalesce is your second step.

left_join(df_main, new_prediction, by="UID") %>%
  mutate(result = coalesce(result.x, result.y)) %>%
  select(-result.x, -result.y)
# # A tibble: 5 x 3
#     UID   foo result
#   <dbl> <chr>  <chr>
# 1     1   moo    Cow
# 2     2   rum   <NA>
# 3     3  oink    Pig
# 4     4  woof    Dog
# 5     5  hiss  Snake

coalesce会接受任意数量的列。如果存在多个非缺失值,则较早出现的列具有优先权。


这正是我一直在寻找的 - 我知道肯定有一种“R”方法可以做到。作为额外的奖励,这甚至适用于超过2个向量的情况,这对我来说非常棒。谢谢! - Thomas

1

除了使用 coalesce,你还可以使用 ifelse手动连接列。

left_join(df_main, new_prediction, by = "UID") %>%
  mutate(result = ifelse(is.na(result.x),result.y, result.x)) %>%
  select(-c(result.x, result.y))
# A tibble: 5 x 3
# UID foo   result
# <dbl> <chr> <chr> 
# 1  1.00 moo   Cow   
# 2  2.00 rum   <NA>  
# 3  3.00 oink  Pig   
# 4  4.00 woof  Dog   
# 5  5.00 hiss  Snake 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接