首页 > 解决方案 > 如何在 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

标签: rformuladplyrnse

解决方案


你试过把括号放在不同的地方吗?例如sym(xvar ^ 2)(!!sym(xvar)) ^ 2

错误消息告诉您这sym(xvar)是非数字的,这是真的。所以你需要应用一元!二进制 ^ 一之前的运算符。

运算符优先级:

https://stat.ethz.ch/R-manual/R-devel/library/base/html/Syntax.html


推荐阅读