我有一个小...
# 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
Run Code Online (Sandbox Code Playgroud)
如果数字列中的值等于 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
Run Code Online (Sandbox Code Playgroud)
我尝试了以下...
df %>% mutate_at(vars(contains("_1")), .funs = list(~if_else(number == 1, NA_real_, .)))
Run Code Online (Sandbox Code Playgroud)
但这没有用。
我主要使用 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
Run Code Online (Sandbox Code Playgroud)
编辑(保留原始值)
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
Run Code Online (Sandbox Code Playgroud)
数据
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
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
607 次 |
| 最近记录: |