I have the following data:
library(dplyr)
d <- data_frame(
region = c('all', 'nj', 'rkl', 'all'),
figures= c(5, 7, 4, 8),
figures2 = c(3, 5, 6, 7))
I would like to use dplyr to say when 'region' = 'all' then turn 'figures' and 'figures2' to 'x'. I don't want to use mutate to create new variables, I want to change the values in the variables that already exist. So the data would look like this:
d2 <- data_frame(
region = c('all', 'nj', 'rkl', 'all'),
figures= c(x, 7, 4, x),
figures2 = c(x, 5, 6, x))
I think I need something like this:
d %>% mutate_at(vars(1:3), funs(ifelse(region = 'all', 'x', .)))
However, this doesn't quite work.
You were on the right path with mutate_at
:
d %>%
mutate_at(vars(2:3), list(~ ifelse(region == 'all', 'x', .)))
Output:
# 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
You can just replace 'x'
with a number if needed.
EDIT.
replace
is a better alternative, you could just do d %>%
mutate_at(vars(2:3), list(~ replace(., region == 'all', 'x')))
as well;list
with newest dplyr
version, so mutate_at(2:3, ~ ifelse(region == 'all', 'x', .))
would do the job as well.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With