Mark Neal
Mark Neal

Reputation: 1204

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

Upvotes: 2

Views: 132

Answers (1)

Simon Woodward
Simon Woodward

Reputation: 2026

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

Upvotes: 1

Related Questions