Mrmoleje
Mrmoleje

Reputation: 493

Mutate multiple variables based on a given condition

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.

Upvotes: 4

Views: 1658

Answers (3)

akrun
akrun

Reputation: 887118

An option would be be also to use case_when

library(dplyr)
d %>%
   mutate_if(is.numeric, list(~ case_when(region == "all" ~ 'x',
                                         TRUE ~ as.character(.) )))
# 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       

A base R compact option would be

d[d$region == "all", -1] <- "x"

Upvotes: 4

arg0naut91
arg0naut91

Reputation: 14764

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.

Upvotes: 8

LyzandeR
LyzandeR

Reputation: 37879

One way with mutate and replace:

d %>% 
  mutate(figures = replace(figures, region == 'all', 10)) %>%
  mutate(figures2 = replace(figures2, region == 'all', 10))

# A tibble: 4 x 3
  region figures figures2
  <chr>    <dbl>    <dbl>
1 all         10       10
2 nj           7        5
3 rkl          4        6
4 all         10       10

I am using 10 here as your x

Upvotes: 4

Related Questions