Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutate multiple variables based on a given condition

Tags:

r

dplyr

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.

like image 366
Mrmoleje Avatar asked Dec 03 '22 18:12

Mrmoleje


1 Answers

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.

  • I also think that replace is a better alternative, you could just do d %>% mutate_at(vars(2:3), list(~ replace(., region == 'all', 'x'))) as well;
  • Moreover, as noted by @Moody_Mudskipper, no need for list with newest dplyr version, so mutate_at(2:3, ~ ifelse(region == 'all', 'x', .)) would do the job as well.
like image 188
arg0naut91 Avatar answered Dec 11 '22 17:12

arg0naut91