我有个小题...
# 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
如果在number列中的值等于1,但仅在以“ _1”结尾的列中(因此X_1和Y_1),我想使所有值等于NA。
我也想在_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
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句