簡體   English   中英

left_join R數據幀,將兩列與NA合並

[英]left_join R dataframes, merging two columns with NAs

我的問題如下:假設我有一個包含以下列的現有數據框:UID,foo,結果。 結果已經部分填充。 現在,第二個模型可以預測其他行,從而生成包含UID和結果列的第二個數據框:(在底部復制的代碼)

## 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 left_join新結果以獲取以下結果列:

## 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"))

coalesce是您的第二步。

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將接受您提供的盡可能多的列。 如果存在多個非缺失值,則較早的列具有優先權。

添加使用的格里高爾的回答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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM