Loess Fit and Resulting Equation

Fit loess smoothers for multiple groups across multiple numeric variables

We can get the data in long format using. pivot_longer, group_by Animal and column name and apply loess to each combinaton.

library(dplyr)
library(tidyr)

TwoVarDF %>%
pivot_longer(cols = starts_with('Var')) %>%
group_by(Animal, name) %>%
mutate(model = loess(value~Day, span = 0.3)$fitted)

loess regression on each group with dplyr::group_by()

You may have already figured this out -- but if not, here's some help.

Basically, you need to feed the predict function a data.frame (a vector may work too but I didn't try it) of the values you want to predict at.

So for your case:

fems <- fems %>% 
group_by(CpG) %>%
arrange(CpG, AVGMOrder) %>%
mutate(Loess = predict(loess(Meth ~ AVGMOrder, span = .5, data=.),
data.frame(AVGMOrder = seq(min(AVGMOrder), max(AVGMOrder), 1))))

Note, loess requires a minimum number of observations to run (~4? I can't remember precisely). Also, this will take a while to run so test with a slice of your data to make sure it's working properly.

R - loess prediction returns NA

From the manual page of predict.loess:

When the fit was made using surface = "interpolate" (the default), predict.loess will not extrapolate – so points outside an axis-aligned hypercube enclosing the original data will have missing (NA) predictions and standard errors

If you change the surface parameter to "direct" you can extrapolate values.

For instance, this will work (on a side note: after plotting the prediction, my feeling is that you should increase the span parameter in the loess call a little bit):

lo <- loess(y~x, control=loess.control(surface="direct"))
predict(lo, newdata=x.all)

How can I customize a loess fit inside a levelplot in R

You can pass extra arguments to the loess method using the args parameter of panel.2dsmoother. Just put the arguments inside a list.

Obviously, we don't have your data, but we can show the concept using the built in data set iris. First, we'll show the plot with the default arguments:

library(lattice)
library(latticeExtra)

levelplot(Sepal.Width ~ Petal.Width * Petal.Length,
iris,
region = TRUE,
col.regions = hcl.colors(110, palette = "spectral", rev = F),
contour = FALSE) +
layer_(panel.2dsmoother(..., n = 400, method = 'loess'))

Sample Image

Now let's use a smaller span value for our loess smoothing:

levelplot(Sepal.Width ~ Petal.Width * Petal.Length, 
iris,
region = TRUE,
col.regions = hcl.colors(110, palette = "spectral", rev = F),
contour = FALSE) +
layer_(panel.2dsmoother(..., n = 400, method = 'loess',
args = list(span = 0.2)))

Sample Image

loess standard error as list object

Like this:

foo<-loess(something)

foo$s


Related Topics



Leave a reply



Submit