Combine logical conditions in mutate_if

Hello, I wonder how I can combine the following conditions in a mutate_if

mutate if:

  • the variable is a character
  • the variable is NOT "var1"

example:

data_frame(var1 = c("hello", 'there'),
           var2 = c("1", "2"),
            var3 = c("4", '5'))
# A tibble: 2 x 3
  var1  var2  var3 
  <chr> <chr> <chr>
1 hello 1     4    
2 there 2     5

mutate_if(vars(-var1) & is.character, as.numeric) fails miserably...

Thanks!

You can achieve that by grouping the data.frame first by the column you do not want the predicate to apply on

library(dplyr, warn.conflicts = FALSE)
data_frame(var1 = c("hello", 'there'),
           var2 = c("1", "2"),
           var3 = c("4", '5')) %>%
  group_by(var1) %>%
  mutate_if(is.character, as.numeric) %>%
  ungroup()
#> # A tibble: 2 x 3
#>   var1   var2  var3
#>   <chr> <dbl> <dbl>
#> 1 hello     1     4
#> 2 there     2     5

Created on 2018-08-08 by the reprex package (v0.2.0).

Otherwise, you can use the at variant by selecting column index or names before thanks to a predicate

library(tidyverse)
df <- data_frame(var1 = c("hello", 'there'),
           var2 = c("1", "2"),
           var3 = c("4", '5'))
to_keep <- df %>% 
  select(-var1) %>%
  map_lgl(is.character) %>%
  names

df %>%
  mutate_at(to_keep, as.numeric)
#> Warning: le package 'bindrcpp' a été compilé avec la version R 3.4.4
#> # A tibble: 2 x 3
#>   var1   var2  var3
#>   <chr> <dbl> <dbl>
#> 1 hello     1     4
#> 2 there     2     5

Created on 2018-08-08 by the reprex package (v0.2.0).

4 Likes