且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用其他 df r 中的值替换数据框中的 na

更新时间:2022-02-18 08:52:30

您可以加入数据并使用 coalesce 选择非 NA 值.

You can join the data and use coalesce to select non-NA value.

library(dplyr)

x %>%
  left_join(y, by = 'Month') %>%
  mutate(Value = coalesce(Value.x, Value.y)) %>%
  select(names(x))

在基础 R 中,您可以merge 并使用 ifelse 选择非 NA 值


In base R, you can merge and use ifelse to select non-NA value

transform(merge(x, y, by = 'Month'), 
          Value = ifelse(is.na(Value.x), Value.y, Value.x))[names(x)]