用数据帧 2 的相应值替换数据帧 1 中的值
Replace values in dataframe 1 with corresponding values of dataframe 2
我有两个数据帧(tibbles):
library(tidyverse)
dat_x <- tribble(
~id, ~month_1, ~month_2,
"A", NA, NA,
"B", NA, 0,
"C", 0, 0
)
dat_y <- tribble(
~id, ~month_1, ~month_2,
"A", 0, 0,
"B", 0, 0,
"C", 0, 30
)
我想用 NA
替换 dat_y
中的单元格,其中 dat_x
中对应的单元格是 NA
。预期输出:
> expected_output
# A tibble: 3 x 3
# id month_1 month_2
# <chr> <dbl> <dbl>
#1 A NA NA
#2 B NA 0
#3 C 0 30
我试过 purrr::map2()
但无法正常工作。
map2(dat_x, dat_y, ~ .y[is.na(.x)] <- NA) #Error: object '.y' not found
有没有人对此有一个优雅的解决方案?越简洁易读越好:).
dat_y[is.na(dat_x)] <- NA
应该够了吧?
我有两个数据帧(tibbles):
library(tidyverse)
dat_x <- tribble(
~id, ~month_1, ~month_2,
"A", NA, NA,
"B", NA, 0,
"C", 0, 0
)
dat_y <- tribble(
~id, ~month_1, ~month_2,
"A", 0, 0,
"B", 0, 0,
"C", 0, 30
)
我想用 NA
替换 dat_y
中的单元格,其中 dat_x
中对应的单元格是 NA
。预期输出:
> expected_output
# A tibble: 3 x 3
# id month_1 month_2
# <chr> <dbl> <dbl>
#1 A NA NA
#2 B NA 0
#3 C 0 30
我试过 purrr::map2()
但无法正常工作。
map2(dat_x, dat_y, ~ .y[is.na(.x)] <- NA) #Error: object '.y' not found
有没有人对此有一个优雅的解决方案?越简洁易读越好:).
dat_y[is.na(dat_x)] <- NA
应该够了吧?