真的很难将dplyr函数放在我的函数中 . 我理解标准评估版本的 function_
后缀,但仍有问题,并且似乎尝试了 eval
paste
和 lazy
的所有组合 .
尝试将多个列除以组的控件的中位数 . 示例数据包括虹膜中的另一列名为“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 回答
如果您还没有,它可能会帮助您阅读标准评估here上的小插图,虽然听起来有些可能很快就会改变 .
您的函数缺少在
mutate_each_
行中使用包lazyeval的interp
. 因为您尝试在funs
中使用变量名称(Control
变量),所以在这种情况下需要funs_
以及interp
. 请注意,这种情况根本不需要mutate_each_
. 如果您在选择要变异的列时尝试使用列名而不是列号,则需要它 .以下是您的函数中的行而不是您拥有的行: