用其他 df r 中的值替换数据框中的 na [英] replace na in a dataframe with value in other df r

查看:61
本文介绍了用其他 df r 中的值替换数据框中的 na的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 df 的一个例子:

This is an example of my df:

x<-tibble::tribble(
  ~ID, ~Month, ~Value,
  "A",     1L,   100L,
  "A",     2L,   200L,
  "A",     3L,     NA,
  "A",     4L,   400L,
  "B",     1L,    50L,
  "B",     2L,    20L,
  "B",     3L,    30L,
  "B",     4L,     NA,
  "C",     1L,     NA,
  "C",     2L,    60L,
  "C",     3L,    70L,
  "C",     4L,    60L,
  "D",     1L,    60L,
  "D",     2L,    60L,
  "D",     3L,    60L,
  "D",     4L,    50L
  )

我还有另一个具有此值的 df:

And I have another df with this values:

y<-tibble::tribble(
  ~Month, ~Value,
      1L,    50L,
      2L,   100L,
      3L,    20L,
      4L,    70L
  )

我需要用 y df 的值替换 x 中的 NA.这正是我所期望的.

I need to replace the NA's in x with the values of the y df. This is what I expect.

xy<- tibble::tribble(
  ~ID, ~Month, ~Value,
  "A",     1L,   100L,
  "A",     2L,   200L,
  "A",     3L,    20L,
  "A",     4L,   400L,
  "B",     1L,    50L,
  "B",     2L,    20L,
  "B",     3L,    30L,
  "B",     4L,    70L,
  "C",     1L,    50L,
  "C",     2L,    60L,
  "C",     3L,    70L,
  "C",     4L,    60L,
  "D",     1L,    60L,
  "D",     2L,    60L,
  "D",     3L,    60L,
  "D",     4L,    50L
  )

有人知道怎么做吗?谢谢!

Does anyone know how to do this? Thanks !

推荐答案

您可以加入数据并使用 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)]

这篇关于用其他 df r 中的值替换数据框中的 na的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆