mutate_each_非标准评估 [英] mutate_each_ non-standard evaluation
问题描述
在我的职能范围内真的很挣扎。我理解标准评估版本的函数_
后缀,但仍然有问题,似乎尝试了 eval
code>粘贴和 lazy
。
Really struggling with putting dplyr functions within my functions. I understand the function_
suffix for the standard evaluation versions, but still having problems, and seemingly tried all combinations of eval
paste
and lazy
.
试图将多个列分开一组的控制中位数。示例数据包括名为Control的虹膜中的另外一列,因此每个物种具有40'正常'和10'对照'。
Trying to divide multiple columns by the median of the control for a group. Example data includes an additional column in iris named 'Control', so each species has 40 'normal', and 10 'control'.
data(iris)
control <- rep(c(rep("normal", 40), rep("control", 10)), 3)
iris$Control <- control
正常dplyr工作正常:
Normal dplyr works fine:
out_df <- iris %>%
group_by(Species) %>%
mutate_each(funs(./median(.[Control == "control"])), 1:4)
尝试将其包装成一个函数:
Trying to wrap this up into a function:
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
我得到错误:...:需要数字数据
推荐答案
如果您还没有,可能会帮助您阅读标准评估版本这里,虽然听起来有些可能会很快改变。
If you haven't already, it might help you to read the vignette on standard evaluation here, although it sounds like some of this may be changing soon.
您的功能在 mutate_each _
行中的包 lazyeval 中缺少使用 interp
。因为您尝试在 funs
中使用变量名称( Control
变量),您需要<$ c $在这种情况下,c> funs _ 以及 interp
。请注意,这是一种您根本不需要 mutate_each _
的情况。如果您在选择要变异的列时尝试使用列名而不是列号,则需要它。
Your function is missing the use of interp
from package lazyeval in the mutate_each_
line. Because you are trying to use a variable name (the Control
variable) in the funs
, you need funs_
in this situation along with interp
. Notice that this is a situation where you don't need mutate_each_
at all. You would need it if you were trying to use column names instead of column numbers when selecting the columns you want to mutate.
这是您的函数,而不是你有的:
Here is what the line would look like in your function instead of what you have:
mutate_each(funs_(interp(~./median(.[x == control_val]), x = as.name(control_col))),
num_cols)
这篇关于mutate_each_非标准评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!