Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr 0.5.0 mutate using column index

Tags:

r

dplyr

I've updated dplyr (now 0.7.1) and a lot of my old code does not work because mutate_each has been deprecated. I use to do something like this (code below) with mutate_each using the column index. I'd do this on hundreds of columns. And I just can't figure out how to use the vars argument correctly with mutate_at. All examples I've seen have been using column names...which I don't want to do. I'm sure it's a simple answer but I've spent too much time trying to figure it out and would appreciate some help very much.

data<-data.frame(numbers=1:10, morenumbers=11:20)
change<-function(x) ifelse(x>10, 1, 2)
newdata<-data%>%mutate_each(funs(change), 1:2)

If I try:

newdata<-data%>%mutate_at(funs(change), vars(1:2))

Or even this:

newdata<-data%>%mutate_at(funs(change), vars(numbers, morenumbers))     

I get the following error

Error: `.vars` must be a character/numeric vector or a `vars()` object, 
not list
like image 511
Kevin Avatar asked Jul 13 '17 16:07

Kevin


1 Answers

The new prototype of mutate_at is:

mutate_at(.tbl, .vars, .funs, ..., .cols = NULL)

Notice, that the .vars is the first argument now. So, either you specify .vars explicitly or change the order.

newdata <- data %>% mutate_at(funs(change), .vars = vars(1:2))
# OR
newdata <- data %>% mutate_at(vars(1:2), funs(change))

   numbers morenumbers
1        2           1
2        2           1
3        2           1
4        2           1
5        2           1
6        2           1
7        2           1
8        2           1
9        2           1
10       2           1
like image 65
m0nhawk Avatar answered Oct 20 '22 06:10

m0nhawk