我怎样才能mutate_if()改变bto的值NA以防万一a > 25
我可以做到ifelse,但我觉得mutate_if是为这样的任务而创建的。
library(tidyverse)
tbl <- tibble(a = c(10, 20, 30, 40, 10, 60),
b = c(12, 23, 34, 45, 56, 67))
Run Code Online (Sandbox Code Playgroud)
在这个小例子中,我不确定您是否真的需要mutate_if(). mutate_if旨在使用该_if部分来确定要子集化和处理哪些列,而不是if修改值时的条件。
相反,您可以mutate_at()根据列的确切名称或使用 来选择要操作的列vars(contains('your_string'))。
有关函数的更多信息,请参阅帮助页面mutate_*:https://dplyr.tidyverse.org/reference/mutate_all.html
这里有 3 个选项,使用mutate()和mutate_at():
# using mutate()
tbl %>%
mutate(
b = ifelse(a > 25, NA, b)
)
# mutate_at - we select only column 'b'
tbl %>%
mutate_at(vars(c('b')), ~ifelse(a > 25, NA, .))
# select only columns with 'b' in the col name
tbl %>%
mutate_at(vars(contains('b')), ~ifelse(a > 25, NA, .))
Run Code Online (Sandbox Code Playgroud)
它们都产生相同的输出:
# A tibble: 6 x 2
a b
<dbl> <dbl>
1 10 12
2 20 23
3 30 NA
4 40 NA
5 10 56
6 60 NA
Run Code Online (Sandbox Code Playgroud)
我知道不是mutate_if,但我怀疑你实际上并不需要它。