r - Pass column name to function from mutate_each -
i'd apply transformation columns via dplyr::mutate_each, e.g.
library(dplyr) mult <- function(x,m) return(x*m) mtcars %>% mutate_each(funs(mult(.,2))) # multiply columns factor of 2
however, transformation should have parameters depending on column name. therefore, column name should passed function additional argument
named.mult <- function(x,colname) return(x*param.a[[colname]])
example: multiply every column different factor:
param.a <- c() param.a[names(mtcars)] <- seq(length(names(mtcars))) param.a # mpg cyl disp hp drat wt qsec vs gear carb # 1 2 3 4 5 6 7 8 9 10 11
since column name gets lost during mutate_each, work around passing list lazy evalution mutate_ (the se version):
library(lazyeval) named.mutate <- function(fun, cols) sapply(cols, function(n) interp(~fun(col, n), fun=fun, col=as.name(n))) mtcars %>% mutate_(.dots=named.mutate(named.mult, names(.)))
works, there special variable .name contains column name of . each colwise execution? like
mtcars %>% mutate_each(funs(named.mult(.,.name)))
i'd suggest taking different approach. instead of using mutate_each
combination of dplyr::mutate
tidyr::gather
, tidyr::spread
can achieve same result.
for example:
library(dplyr) library(tidyr) data(mtcars) # multiple each column different interger mtcars %>% dplyr::tbl_df() %>% dplyr::mutate(make_and_model = rownames(mtcars)) %>% tidyr::gather(key, value, -make_and_model) %>% dplyr::mutate(m = as.integer(factor(key)), # multiplication factor dependent on column name value = value * m) %>% dplyr::select(-m) %>% tidyr::spread(key, value) # compare original data mtcars[order(rownames(mtcars)), order(names(mtcars))] # muliplicative values used. mtcars %>% tidyr::gather() %>% dplyr::mutate(m = as.integer(factor(key))) %>% dplyr::select(-value) %>% dplyr::distinct()
Comments
Post a Comment