mutate_each_非标准评估

时间:2016-03-23 14:32:16

标签: r dplyr

真的很难将dplyr函数放在我的函数中。我理解标准评估版本的function_后缀,但仍然遇到问题,并且似乎尝试了eval pastelazy的所有组合。

尝试将多个列除以组的控件的中位数。示例数据包括虹膜中另一个名为“Control”的列,因此每个物种都有40'正常'和10'控制'。

data(iris)
control <- rep(c(rep("normal", 40), rep("control", 10)), 3)
iris$Control <- control

正常dplyr工作正常:

out_df <- iris %>% 
    group_by(Species) %>% 
    mutate_each(funs(./median(.[Control == "control"])), 1:4)

尝试将其包装成一个函数:

norm_iris <- function(df, control_col, control_val, species, num_cols = 1:4){

out <- df %>%
    group_by_(species) %>% 
    mutate_each_(funs(./median(.[control_col == control])), num_cols)
    return(out)
}

norm_iris(iris, control_col = "Control", control_val = "control", species = "Species")

我收到错误:

Error in UseMethod("as.lazy_dots") : 
no applicable method for 'as.lazy_dots' applied to an object of class "c('integer', 'numeric')"

使用funs_代替funs我得到Error:...: need numeric data

1 个答案:

答案 0 :(得分:1)

如果您还没有,可能会帮助您阅读标准评估here上的插图,虽然听起来有些情况可能会很快发生变化。

您的功能缺少在interp行中使用 lazyeval 包中的mutate_each_。由于您尝试在Control中使用变量名称(funs变量),因此在这种情况下您需要funs_以及interp。请注意,这种情况下您根本不需要mutate_each_。如果您在选择要变异的列时尝试使用列名而不是列号,则需要它。

以下是您的函数中的行而不是您拥有的行:

mutate_each(funs_(interp(~./median(.[x == control_val]), x = as.name(control_col))), 
                        num_cols)
相关问题