将列名称传递给mutate_each

时间:2015-10-22 13:20:39

标签: r dplyr

我希望通过 dplyr :: mutate_each 对所有列应用转换,例如

library(dplyr)
mult <- function(x,m) return(x*m)
mtcars %>% mutate_each(funs(mult(.,2)))    # Multiply all columns by a factor of two

但是,转换应具有取决于列名称的参数。因此,列名应作为附加参数传递给函数

named.mult <- function(x,colname) return(x*param.A[[colname]])

示例:将每列乘以不同的因子:

param.A <- c()
param.A[names(mtcars)] <- seq(length(names(mtcars)))
param.A
# mpg  cyl disp   hp drat   wt qsec   vs   am gear carb 
#   1    2    3    4    5    6    7    8    9   10   11 

由于在 mutate_each 期间列名丢失,我目前通过将带有延迟评估的列表传递给 mutate _ (SE版本)来解决此问题:

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,但是有一些特殊的变量,比如 .name ,它包含的列名,用于每个colwise执行吗?所以我可以做类似

的事情
mtcars %>% mutate_each(funs(named.mult(.,.name)))

1 个答案:

答案 0 :(得分:0)

我建议采取不同的方法。 mutate_eachdplyr::mutatetidyr::gather的组合可以实现相同的结果,而不是tidyr::spread

例如:

library(dplyr)
library(tidyr)

data(mtcars)

# Multiple each column by a 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)),   # a multiplication factor dependent on column name
                value = value * m) %>% 
  dplyr::select(-m) %>%
  tidyr::spread(key, value)

# compare to the original data
mtcars[order(rownames(mtcars)), order(names(mtcars))]

# the muliplicative values used.
mtcars %>% 
  tidyr::gather() %>% 
  dplyr::mutate(m = as.integer(factor(key))) %>% 
  dplyr::select(-value) %>%
  dplyr::distinct()