如何在 mutate 中以编程方式使用多项式函数?

How can you use a polynomial function programmatically in 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