daverous
daverous

Reputation: 101

loop "functions" and "for loops" through list of dataframes

Hy. I'm working with shapefiles in R. I wrote a script which processes one of my shapefiles. Therefore I wrote mutliple functions and for loops. After processing the shapefile it will be written to another folder. Now i need to apply this to all my shapefiles. Is there an easy way to do this? I'm new to R.

What I've got sofar: Script for one shapefile, which looks like this: Upload the file and set time format:

setwd("")
shape=ReadOGR(dsn=", layer= "Trip_2")
shape$Zeit= as.POSIXct(strptime(shape$Zeit_txt, format= "%d.%m.%Y%H:%M:%S", tz="GMT"), tz="GMT")

First extractions: make Wegtyp NA if Count is not 1

shape$wegtyp[shape$Count != 1] = NA
shape$name_wegty[shape$Count != 1] = NA
shape$OBJECTVAL[shape$Count != 1] = NA
shape$name_weg_1[shape$Count != 1] = NA

First Function:

calculateDistancesWGS = function(long, lat){
  distWGS = long
  distWGS = NA
  for (i in 1:(length(lat)-1)){
    distWGS[i+1] = distCosine( c(long[i+1], lat[i+1]), c(long[i], lat[i]))
  }
  return(distWGS)
}

shape$distanceWGS = calculateDistancesWGS(shape$longitude, shape$latitude)

several more function follow

extract file as shapefile:

 writeOGR(shape, dsn= "", layer= "Trip_03", driver= "ESRI Shapefile" )

Now I need to do this with all my shapefiles and save them with different names. I'm able to import several shapefiles to R creating a list of dataframes like this:

 setwd("")
list_shp <-        list.files(path="", pattern="*.shp", full.names = TRUE,
                       recursive = TRUE, include.dirs = FALSE)
shapes <- lapply(list_shp, function(x) {readOGR(dsn=x,     layer=ogrListLayers(x))})

But when it gets to applying the timeformat and the functions i could not figure out what to do.

Here's a short example of my data:

d1= data.frame(longitude=(10.42206), latitude= (46.60109), Wegtyp= (1),     Zeit_txt= 14.50)
d2= data.frame (longitude= (10.42207), latitude= (46.60108), Wegtyp= 2, Zeit_txt= (14.55))

Any help would be highly appreciated

Upvotes: 0

Views: 287

Answers (1)

Frank
Frank

Reputation: 2416

You can just lapply a function that does the command you wanted, like the following:

addTime <- function(shape) { 
  shape$Zeit= as.POSIXct(strptime(shape$Zeit_txt, format= "%d.%m.%Y%H:%M:%S", tz="GMT"), tz="GMT")
  return(shape)
}
shapes <- lapply(shapes, addTime)

Upvotes: 1

Related Questions