R tidyverse 相当于 Stata 如果丢失则替换

R tidyverse equivalent to Stata replace if missing

我正在尝试找到一个 R/tidyverse 相当于 Stata 的 replace b = a if missing(b)

假设我有这些数据:

library(tidyverse)
data <- data.frame(a=c(1:8), b= c(1:5, NA, NA, NA))

我正在尝试用 a 中的值替换 b 中的缺失值。我试试这个:

data %<>% mutate(b = replace_na(b, a))

但是报错。在 tidyverse 我可以做什么来解决这个问题?

您可以简单地在 mutate 中使用 ifelse:

data %>% 
  mutate(b = ifelse(is.na(b), a, b))
#>   a b
#> 1 1 1
#> 2 2 2
#> 3 3 3
#> 4 4 4
#> 5 5 5
#> 6 6 6
#> 7 7 7
#> 8 8 8

reprex package (v0.3.0)

创建于 2020-03-21

按照你的做法,我会使用 dplyr 中的 coalesce:

data %<>% mutate(b = coalesce(b, a))

输出:

data

  a b
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
7 7 7
8 8 8

data.table中,一个选项是fcoalesce

library(data.table)
setDT(data)[, b  := fcoalesce(b, a)]