Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude columns by names in mutate_at in dplyr

Tags:

r

dplyr

I am trying to do something very simple, and yet can't figure out the right way to specify. I simply want to exclude some named columns from mutate_at. It works fine if I specify position, but I don't want to hard code positions.

For example, I want the same output as this:

mtcars %>% mutate_at(-c(1, 2), max)

But, by specifying mpg and cyl column names.

I tried many things, including:

mtcars %>% mutate_at(-c('mpg', 'cyl'), max)

Is there a way to work with names and exclusion in mutate_at?

like image 419
Gopala Avatar asked Jun 13 '17 23:06

Gopala


2 Answers

You can use vars to specify the columns, which works the same way as select() and allows you to exclude columns using -:

mtcars %>% mutate_at(vars(-mpg, -cyl), max)
like image 195
Marius Avatar answered Oct 19 '22 15:10

Marius


One option is to pass the strings inside one_of

mtcars %>% 
     mutate_at(vars(-one_of("mpg", "cyl")), max)
like image 10
akrun Avatar answered Oct 19 '22 13:10

akrun