[英]dplyr NSE: Centering multiple columns in a dataframe
I am trying to "center" multiple columns in a dataframe using dplyr but I keep getting a "non-numeric argument to binary operator" evaluation error.我正在尝试使用 dplyr 将数据框中的多列“居中”,但我不断收到“二元运算符的非数字参数”评估错误。 I think it is because I am trying to pass a string in when my function expects a bare variable name.
我认为这是因为当我的函数需要一个裸变量名时,我试图传入一个字符串。 However, using the syms() function does not help.
但是,使用 syms() 函数无济于事。
center <- function(var) {
var <- enquo(var)
var_ctrd <- paste0(quo_name(var), "_ctrd")
dataset <- dataset %>%
group_by(Gender) %>%
mutate(!! var_ctrd := !! var - mean(!! var, na.rm = TRUE))
}
# Pull out character vector of modifier names
mod_names <- dataset %>%
select(NeckLengthCm:FlexExtDiff_Peak_abs) %>%
colnames()
# Iterate over modifiers
walk(syms(mod_names), center)
Does anyone know how to solve this or if there is a better solution?有谁知道如何解决这个问题或者是否有更好的解决方案?
You can use mutate_at()
to center a subset of variables using a vector of variable names您可以使用
mutate_at()
使用变量名称向量将变量子集居中
# Only center a subset
vars <- colnames(mtcars)[1:4]
mtcars %>%
mutate_at(vars, scale, scale = FALSE)
I have another suggestion within the mutate_at
:我在
mutate_at
有另一个建议:
mtcars %>%
mutate_at(.vars = colnames(mtcars)[1:4],
.funs = list("scaled" = scale))
Here you get exactly what you wanted.在这里你得到你想要的。 Scaled variables in new columns with suffix.
带有后缀的新列中的缩放变量。
mpg cyl disp hp drat wt qsec vs am gear carb mpg_scaled cyl_scaled disp_scaled hp_scaled
1 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 0.1508848 -0.1049878 -0.57061982 -0.5350928
2 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 0.1508848 -0.1049878 -0.57061982 -0.5350928
3 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 0.4495434 -1.2248578 -0.99018209 -0.7830405
4 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 0.2172534 -0.1049878 0.22009369 -0.5350928
5 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 -0.2307345 1.0148821 1.04308123 0.4129422
6 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 -0.3302874 -0.1049878 -0.04616698 -0.6080186
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.