问题描述
我想使用mutate根据预先定义的具有二次/多项式函数的变量为我提供预测值.我可以使用这样的线性公式轻松地做到这一点:
I want to use mutate to give me predicted values based on pre-specified variables with a quadratic / polynomial function. I can easily do this with a linear formula like this:
library(tidyverse)
xvar <- "Sepal.Length"
yvar <- "Sepal.Width"
##linear fit
#what does formula text look like?
formula = !!sym(yvar) ~ !!sym(xvar)
formula
models <- iris %>%
nest(-Species) %>%
mutate(
# Perform loess (or lm) calculation on each group
m = map(data, lm,
formula = !!sym(yvar) ~ !!sym(xvar) ),
# Retrieve the fitted values from each model
fitted = map(m, `[[`, "fitted.values")
)
但是,尝试使用多项式公式建模会产生错误.我在做什么错了?
However, trying to model with a polynomial formula creates an error. What am I doing wrong?
##polynomial fit
#what does formula text look like?
formula = !!sym(yvar) ~ !!sym(xvar) + I(!!sym(xvar)^2)
formula
#Doesn't work
models <- iris %>%
nest(-Species) %>%
mutate(
# Perform loess (or lm) calculation on each group
m = map(data, lm,
formula = !!sym(yvar) ~ !!sym(xvar) + I(!!sym(xvar)^2)),
#formula = Sepal.Length ~ Sepal.Width + I(Sepal.Width^2)), #works
# Retrieve the fitted values from each model
fitted = map(m, `[[`, "fitted.values")
)
#Error in sym(xvar)^2 : non-numeric argument to binary operator
推荐答案
您是否尝试过将方括号放在其他位置?例如sym(xvar ^ 2)
还是(!!sym(xvar)) ^ 2
?
Have you tried putting the brackets in different places? e.g. sym(xvar ^ 2)
or (!!sym(xvar)) ^ 2
?
错误消息告诉您sym(xvar)
是非数字的,这是正确的.因此,您需要应用一元!运算符之前的二进制^一.
The error messages is telling you that sym(xvar)
is non numeric, which is true. So you need to apply the unary !! operator before the binary ^ one.
操作员优先级:
https://stat.ethz .ch/R-manual/R-devel/library/base/html/Syntax.html
这篇关于如何在mutate中以编程方式使用多项式函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!