简体   繁体   中英

Update table with another table values (several columns) in R

I am trying in R to update a table A with another table B only when values in table B are not NA. For example, if table A is:

表 A

and table B is:

表 B

I would like to have, as a result:

在此处输入图像描述

Would anyone the best way to do that?

library(tidyverse)
A <- tribble(
  ~ name, ~X1, ~X2, ~X3,
  "AX", 1, 1, NA,
  "BL", 6, 1, 3,
  "CD",NA, 4, 6,
  "DA", 4, NA, NA)

B <- tribble(
  ~ name, ~X1, ~X2, ~X3,
  "AX", 4, 5, 6,
  "BL", NA, 3, 4,
  "DA", NA, 4, 6)

bind_rows(A, B) %>% 
  group_by(name) %>% 
  summarise(across(everything(), ~ ifelse(!is.na(last(.)), last(.), first(.))))

  name     X1    X2    X3
  <chr> <dbl> <dbl> <dbl>
1 AX        4     5     6
2 BL        6     3     4
3 CD       NA     4     6
4 DA        4     4     6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM