One_of (vector) inside mutate_each no result found in object
I have a small dataset called a test, where I want to perform some mutate operation on columns defined in the cm vector.
Install and download some packages
require(devtools)
devtools::install_github("hadley/dplyr")
require(dplyr)
First create a test dataframe
test <- data.frame(col1 = c(1,1),
col2=as.character(c(2,2)),
col3=as.character(c(3,3)), stringsAsFactors=F)
Then we create a vector cm
cm <- c("col2", "col3")
Now I can select columns in cm with
test %>% select(one_of(cm))
but when I want to perform an operation, say as.numeric, I get an error.
> test %>% mutate_each(funs(as.numeric), one_of(cm))
Error in one_of(vars, ...) : object 'cm' not found
I can insert the vector manually though
test %>% mutate_each(funs(as.numeric), one_of("col2","col3")) %>% str()
'data.frame': 2 obs. of 3 variables:
$ col1: num 1 1
$ col2: num 2 2
$ col3: num 3 3
Is this a bug or a feature? Am I missing something? Any other ways to do this?
Thank! Martin
+3
source to share
1 answer
You will need to install and download the package lazyeval
and then you can use one of the following options:
require(lazyeval)
require(dplyr)
test %>%
mutate_each_(funs(as.numeric), interp(~one_of(cm), var = as.name(cm))) %>%
str()
Or a shorter version:
test %>% mutate_each_(funs(as.numeric), cm) %>% str()
Both will do the same in this case.
+3
source to share