簡體   English   中英

通過數據幀列表循環“功能”和“ for循環”

[英]loop “functions” and “for loops” through list of dataframes

HY。 我正在R中使用shapefile。我編寫了一個腳本來處理我的shapefile之一。 因此,我編寫了多個函數和for循環。 處理shapefile之后,它將被寫入另一個文件夾。 現在,我需要將其應用於所有shapefile。 是否有捷徑可尋? 我是R的新手。

我所擁有的:一個shapefile的腳本,如下所示:上傳文件並設置時間格式:

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")

第一次提取:如果Count不為1,則使Wegtyp NA

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

第一個功能:

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)

接下來的幾個功能

將文件提取為shapefile:

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

現在,我需要對所有shapefile進行此操作,並用不同的名稱保存它們。 我能夠將幾個shapefile導入到R中,以創建如下所示的數據幀列表:

 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))})

但是,當要應用時間格式和功能時,我不知道該怎么做。

這是我的數據的簡短示例:

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))

任何幫助將不勝感激

您可以lapply一個執行所需命令的函數,如下所示:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM