Joe Slow
Joe Slow

Reputation: 11

y for x from loess, but get error with predict

I have some stream cross section data. It's looks like:

width
 [1]  0.00  0.00  1.85  4.00  5.70  6.40  7.40  8.00  9.70 10.70 12.20 14.00 16.65 18.00 18.80 19.55 20.17
[18] 20.17

depth
 [1]  0.000  0.185  0.310  0.550  0.720  1.110  1.490  1.740  1.810  2.000  1.920  1.680  1.530  0.600
[15] -0.620 -0.760 -0.830 -0.998

I want to plot the points, connect the dots, then calculate y values for a standard x, like every .5 meter. I can make this happen using smooth.spline, but using loess actually just connects the dots.

Here is what I tried

plot(width, depth)
connectlines=lowess(depth[-c(1, length(depth))]~width[-c(1,length(width))], f=1/8)
lines(connectlines)

Because the first and last depth measurements are at a reference pin I dropped them.

Then I try to find a value before I apply it to .5m increments.

predict(connectlines, 4)

And I get the following error:

Error in UseMethod("predict") :
no applicable method for 'predict' applied to an object of class "list"

What's up? Seems simple. Right. I also need to figure the length of the arc made from connecting the points if anyone has help with that as well. I've tried arclength but that doesn't work without a function. I'm using AUC for the area and it works fine.

Upvotes: 1

Views: 230

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76450

The following code uses function loess, not lowess.
According to the help page of lowess, section See Also, this function is

See Also

loess, a newer formula based version of lowess (with different defaults!).

The argument f becomes the span of the points used in the fit. I have set span = 0.5.

df1 <- data.frame(width, depth)
fit <- loess(depth ~ width, data = df1[-c(1, nrow(df1)),], span = 0.5)

new <- data.frame(width = seq(min(width), max(width), by = 0.5))
new$depth <- predict(fit, newdata = new)

plot(depth ~ width, df1)
lines(fit)
lines(depth ~ width, new, col = "blue")

enter image description here

Data.

width <- scan(text = '
0.00  0.00  1.85  4.00  5.70  6.40  7.40  8.00  9.70 
10.70 12.20 14.00 16.65 18.00 18.80 19.55 20.17 20.17')

depth <- scan(text = '
0.000  0.185  0.310  0.550  0.720  1.110  1.490  1.740  1.810  
2.000  1.920  1.680  1.530  0.600  -0.620 -0.760 -0.830 -0.998')

Upvotes: 1

Related Questions