我有一个小问题......
# A tibble: 20 x 6
id X_1 Y_1 number X_2 Y_2
<int> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 1 3 1 1 3
2 1 1 3 0 1 3
3 2 2 4 1 2 4
4 2 2 4 0 2 4
5 3 1 3 1 1 3
6 3 1 3 0 1 3
如果数字列中的值等于 1,我想让所有值都等于 NA,但仅在以“_1”结尾的列中(因此 X_1 和 Y_1)。
我还想在 _2 列中做相反的事情(即数字等于零的行变为 NA)。
它最终应该看起来像这样......
# A tibble: 20 x 6
id X_1 Y_1 number X_2 Y_2
<int> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 NA NA 1 1 3
2 1 1 3 0 1 3
3 2 NA NA 1 2 4
4 2 2 4 0 2 4
5 3 NA NA 1 1 3
6 3 1 3 0 1 3
我尝试了以下...
df %>% mutate_at(vars(contains("_1")), .funs = list(~if_else(number == 1, NA_real_, .)))
但这没有用。
我主要使用 tidyverse 工作,因此 tidyverse 解决方案会更可取。
最佳答案
这里的解决方案实际评估变量 number
是 0 还是 1(以前的解决方案评估以“_1”或“_2”结尾的变量是 1 还是 0)。
library(dplyr)
df %>%
mutate(across((ends_with("_1")), ~ na_if(number, 1)),
(across((ends_with("_2")), ~ na_if(number, 0))))
# A tibble: 6 x 6
id X_1 Y_1 number X_2 Y_2
<int> <int> <int> <int> <int> <int>
1 1 NA NA 1 1 1
2 1 0 0 0 NA NA
3 2 NA NA 1 1 1
4 2 0 0 0 NA NA
5 3 NA NA 1 1 1
6 3 0 0 0 NA NA
编辑(保留原始值)
df %>%
mutate(across((ends_with("_1")), ~if_else(number == 1, NA_integer_, .))) %>%
mutate(across((ends_with("_2")), ~if_else(number == 0, NA_integer_, .)))
# A tibble: 6 x 6
id X_1 Y_1 number X_2 Y_2
<int> <int> <int> <int> <int> <int>
1 1 NA NA 1 1 3
2 1 1 3 0 NA NA
3 2 NA NA 1 2 4
4 2 2 4 0 NA NA
5 3 NA NA 1 1 3
6 3 1 3 0 NA NA
数据
df <- tibble::tribble(
~id, ~X_1, ~Y_1, ~number, ~X_2, ~Y_2,
1L, 1L, 3L, 1L, 1L, 3L,
1L, 1L, 3L, 0L, 1L, 3L,
2L, 2L, 4L, 1L, 2L, 4L,
2L, 2L, 4L, 0L, 2L, 4L,
3L, 1L, 3L, 1L, 1L, 3L,
3L, 1L, 3L, 0L, 1L, 3L
)
关于根据不同列中的值将多列中的值替换为 NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62387667/