How can you use a polynomial function programmatically in mutate?

笑着哭i 提交于 2020-06-16 04:17:48

问题


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

回答1:


Have you tried putting the brackets in different places? e.g. sym(xvar ^ 2) or (!!sym(xvar)) ^ 2?

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.

Operator precedence:

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



来源:https://stackoverflow.com/questions/61903163/how-can-you-use-a-polynomial-function-programmatically-in-mutate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!