r - 如何在 mutate 中以编程方式使用多项式函数?
问题描述
我想使用 mutate 给我基于预先指定的变量和二次/多项式函数的预测值。我可以用这样的线性公式轻松做到这一点:
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")
)
但是,尝试使用多项式公式进行建模会产生错误。我究竟做错了什么?
##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
?
错误消息告诉您这sym(xvar)
是非数字的,这是真的。所以你需要应用一元!二进制 ^ 一之前的运算符。
运算符优先级:
https://stat.ethz.ch/R-manual/R-devel/library/base/html/Syntax.html
推荐阅读
- woocommerce - Woocommerce - 删除去年未订购的客户
- python - User input in already given range for Python pattern
- firebase - __layout.svelte 的 onMount 完成后运行页面的 onMount
- javascript - 如何在复选框单击时更改 div 边框颜色
- java - 如何检查由 Java Complire 隐式编写的 Java 内部代码
- reactjs - 何时为 redux thunk 额外的减速器更新状态或返回 action.payload?
- c# - 通过 git 自动设置 msbuild nuget pack 目标的版本
- ios - iOS 15 Safari - 如何以编程方式检测标签栏或单个标签选择?
- r - 剪贴板无法访问
- azure-devops - 如何构建一个脚本,允许我使用新的 NPM 版本来定位标签,以便能够合并到一个或多个分支中?