我有以下数据:
library(dplyr)
d <- data_frame(
region = c('all', 'nj', 'rkl', 'all'),
figures= c(5, 7, 4, 8),
figures2 = c(3, 5, 6, 7))
Run Code Online (Sandbox Code Playgroud)
我想用dplyr来表示“区域” =“全部”时,然后将“数字”和“数字2”设置为“ x”。我不想使用mutate创建新变量,而是要更改已经存在的变量中的值。因此数据如下所示:
d2 <- data_frame(
region = c('all', 'nj', 'rkl', 'all'),
figures= c(x, 7, 4, x),
figures2 = c(x, 5, 6, x))
Run Code Online (Sandbox Code Playgroud)
我想我需要这样的东西:
d %>% mutate_at(vars(1:3), funs(ifelse(region = 'all', 'x', .)))
Run Code Online (Sandbox Code Playgroud)
但是,这不太起作用。
您选择了正确的道路mutate_at
:
d %>%
mutate_at(vars(2:3), list(~ ifelse(region == 'all', 'x', .)))
Run Code Online (Sandbox Code Playgroud)
输出:
# A tibble: 4 x 3
region figures figures2
<chr> <chr> <chr>
1 all x x
2 nj 7 5
3 rkl 4 6
4 all x x
Run Code Online (Sandbox Code Playgroud)
您可以'x'
根据需要替换为数字。
编辑。
replace
是一个更好的选择,您也可以这样做d %>%
mutate_at(vars(2:3), list(~ replace(., region == 'all', 'x')))
。list
最新dplyr
版本,因此mutate_at(2:3, ~ ifelse(region == 'all', 'x', .))
也可以完成此工作。