tassones
tassones

Reputation: 1692

LOESS works in ggplot2 but function does not work on its own

When I create a figure in ggplot2 and fit a loess model to the data using stat_smooth(method = 'loess') there is no problem. However, when I use the same data to fit a loess model using the loess() function, I get error messages. Why does loess work in ggplot2 but not in the loess() function? How can I get the loess() function to work with my data?

Example Data

df <- data.frame(matrix(ncol = 2, nrow = 15))
colnames(df)[1:2] <- c("date", "fraction")
df$date <- c("2020-07-15", "2020-08-17", "2020-09-16", "2020-10-14", "2021-05-25",
             "2021-06-23", "2021-07-21", "2021-08-19", "2021-09-20", "2021-10-20",
             "2022-04-20", "2022-05-17", "2022-06-13", "2022-07-13", "2022-08-10")
df$date <- as.Date(df$date, format = "%Y-%m-%d")
df$fraction <- c(7.0,  1.1,  0.0,  4.9, 41.0, 50.7, 53.4,
                 51.2, 37.0, 54.4, 60.4, 75.0, 98.8, 92.1, 97.0)
df

ggplot2 figure showing loess works with the example data

library(ggplot2)

ggplot(df, aes(x = date, y = fraction)) +
  geom_point() +
  stat_smooth(method = "loess")

loess() function not working with the example data. How can I get the loess() function to work with the example data? Ultimately what I am after is the r-squared value of the loess model fit in the above figure.

aa <- loess(fraction~date, data = df)

Upvotes: 0

Views: 38

Answers (1)

Julien
Julien

Reputation: 1695

You could try to convert the Date format to a numeric format

aa <- loess(fraction ~ as.numeric(date), data = df)

Upvotes: 1

Related Questions