简体   繁体   中英

How to update dataset in R

Df1:

ID   Score   Test
1     97        1
1     98        2 
2     85        1
2     NA        2
3     NA        1
3     79        2

Df2:

ID   Score      Test
2    70           2
3    60           1

Desired result:

ID   Score   Test
1     97        1
1     98        2 
2     85        1
2     70        2
3     60        1
3     79        2

I actually have a larger dataframe and a total of 5 tests. I want to update the NA scores in DF1 using the scores in DF2. How do I do this in R?

Does this work:

library(dplyr)
df %>% left_join(df1, by = c('ID','Test')) %>% 
   mutate(Score = coalesce(Score.x, Score.y)) %>% 
   select(-2,-4) %>% relocate(1,3,2)
# A tibble: 6 x 3
     ID Score  Test
  <dbl> <dbl> <dbl>
1     1    97     1
2     1    98     2
3     2    85     1
4     2    70     2
5     3    60     1
6     3    79     2

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