Skip to content
Prev 23288 / 29559 Next

How to plot multiple semi-variogram from a single dataset efficiently in R?

Uzzal,
I see that in your lapply() call you create an object called 'plot'. 
This is bad practice as 'plot' is reserved for a function call in base R 
and may get you in trouble in certain circumstances. That is why in the 
code I gave you (and in the code that follows) this object is called 
'plt' rather than plot.

The following will create a variogram for every hour of each day, label 
them according to YYYY-mm-dd HH:MM:SS (standard POSIX datetime format) 
and save each as a file following a naming convetion of 
'plot_YYYYmmddHH.png' to avoid spaces in the file names.

library(sp)
library(gstat)
library(rgdal)
library(automap)
library(latticeExtra)

seoul311 <- read.csv("Downloads/seoul1to7.csv")
seoul311 <- na.omit(seoul311)

### first we split seoul311 by time into a list rather than subsetting 
manually
seoul311_splt <- split(seoul311, seoul311$time)

a<-as.POSIXct(names(seoul311_splt), format="%Y%m%d%H")
a

vars <- lapply(seq(seoul311_splt), function(i) {

   dat <- seoul311_splt[[i]]
   coordinates(dat) <- ~LON+LAT
   proj4string(dat) <- "+proj=longlat +datum=WGS84"
   dat <- spTransform(dat, CRS("+proj=utm +north +zone=52 +datum=WGS84"))

   variogram <- autofitVariogram(PM10 ~ 1, dat)

   plt <- plot(variogram, plotit = FALSE, asp = 1)
   plt <- update(plt, main = paste("Variogram for", as.character(a[i])))

   return(plt)
})

for (i in seq(names(seoul311_splt))) {
   png(paste0("plot_", names(seoul311_splt)[i], ".png"),
       width = 25, height = 25, units = "cm", res = 300)
   print(vars[[i]])
   dev.off()
}


HTH
Tim
On 27.08.2015 12:25, Uzzal wrote: