2

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
Mark Neal
  • 996
  • 16
  • 52
  • 3
    Have you tried putting the brackets in different places? e.g. sym(xvar ^ 2), or (!!sym(xvar)) ^ 2, etc... 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. – Simon Woodward May 20 '20 at 00:41
  • 2
    Holy brackets Batman - while I tried a bunch of different options, an extra set like so `formula = !!sym(yvar) ~ !!sym(xvar) + I((!!sym(xvar))^2)` works. Did you want to make that an answer? – Mark Neal May 20 '20 at 00:44

1 Answers1

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

Simon Woodward
  • 1,946
  • 1
  • 16
  • 24