Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to build a loess model in in R using time series data

Tags:

r

I have this data frame:

dput(head(y1,20))

structure(list(time = structure(c(1373256120, 1373256360, 1373256660, 
1373256960, 1373257260, 1373257560, 1373257860, 1373258220, 1373258460, 
1373258760, 1373259060, 1373259360, 1373259660, 1373259960, 1373260260, 
1373260620, 1373260860, 1373261160, 1373261460, 1373261760), class = c("POSIXct", 
"POSIXt"), tzone = "America/New_York"), cpu = c(2.5803, 2.7954, 
3.0855, 2.6414, 2.4603, 2.2053, 3.2352, 2.2437, 2.0264, 1.9006, 
4.331, 2.068, 1.999, 1.8115, 1.8955, 1.7475, 1.8565, 2.1557, 
1.9113, 1.3635)), .Names = c("time", "cpu"), row.names = c(NA, 
20L), class = "data.frame")

I am trying to build a loess model as folows:

ls<-loess(cpu~time, data=y1)

I get this error:

Error in simpleLoess(y, x, w, span, degree, parametric, drop.square, normalize,  : 
  NA/NaN/Inf in foreign function call (arg 2)
In addition: Warning message:
In simpleLoess(y, x, w, span, degree, parametric, drop.square, normalize,  :
  NAs introduced by coercion

What am I missing here?

like image 990
user1471980 Avatar asked Jul 08 '13 16:07

user1471980


1 Answers

You should convert your variables to numeric and ensure that they are finite.

with(y1,{
  ok <- is.finite(time) & is.finite(cpu)
  x <- as.numeric(time)[ok]   ## you reproduce  the error without coercion 
  y <- as.numeric(cpu)[ok]
  data <- list(x = x, y = y)
  loess( y~x,data = data)
})

loess(formula = y ~ x, data = data)
Number of Observations: 20 
Equivalent Number of Parameters: 4.42 
Residual Standard Error: 0.6174 

Using panel.smoother from latticeExtra you can get the result without any manipulation(it should do the the job above internally)

library(latticeExtra)
xyplot(cpu ~ time ,type='l',data=y1)+
  layer(panel.smoother(y ~ x, span = 0.75),style=2)

enter image description here

like image 189
agstudy Avatar answered Nov 14 '22 22:11

agstudy