2014-01-07 3 views
0

최근에 R로 작업하기 시작했습니다.이 질문은 아마도 간단한 해결책 일 것입니다. 다른 장면의 일부 .tif 위성 이미지가 있습니다. 테스트 래스터 브릭을 만들 수는 있지만 엄청난 양의 파일 때문에 프로세스를 자동화해야합니다. 따라서 저는 .tif 파일 목록을 읽고 래스터 목록을 출력하는 함수를 만들려고했습니다. 당신은 내가 사용하고 여기에 코드를 아래 찾을 수 있습니다R 문자에 래스터 함수 적용

# Description: Prepare a raster brick with ordered acquisitions 
# from all the scenes of the study area 

library(raster) 
library(rgdal) 
library(sp) 
library(rtiff) 

rm(list = ls()) 

setwd=getwd() 

# If you want to download the .tif files of the 2 scenes from dropbox: 
dl_from_dropbox <- function(x, key) { 
    require(RCurl) 
    bin <- getBinaryURL(paste0("https://dl.dropboxusercontent.com/s/", key, "/", x), 
         ssl.verifypeer = FALSE) 
    con <- file(x, open = "wb") 
    writeBin(bin, con) 
    close(con) 
    message(noquote(paste(x, "read into", getwd())))       
} 

dl_from_dropbox("lndsr.LT52210611985245CUB00-vi.NDVI.tif", "qb1bap9rghwivwy") 
dl_from_dropbox("lndsr.LT52210611985309CUB00-vi.NDVI.tif", "sbhcffotirwnnc6") 
dl_from_dropbox("lndsr.LT52210611987283CUB00-vi.NDVI.tif", "2zrkoo00ngigfzm") 

dl_from_dropbox("lndsr.LT42240631992198XXX02-vi.NDVI.tif", "gx0ctxn2mca3u5v") 
dl_from_dropbox("lndsr.LT42240631992214XXX02-vi.NDVI.tif", "pqnjw2dpz9beeo5") 
dl_from_dropbox("lndsr.LT52240631986157CUB02-vi.NDVI.tif", "rrka10yaktv8la8") 


# 1- Create a list of .tif files with names ordered chronologically (for time series analysis later on) 
pathdir= # change 
# List all the images from any scene in that folder and 
# make a dataframe with a column for the date 
a <- list.files(path=pathdir,pattern="lndsr.LT", all.files=FALSE,full.names=FALSE) 
a1 <- as.data.frame(a, row.names=NULL, optional=FALSE, stringsAsFactors=FALSE) # class(a1$a) # character 
# Create date column with julean date and order it in ascending order 
a1$date <- substr(a1$a, 16, 22) # class(a1$date) = character 
a1 <- a1[order(a1$date),] 
# Keep only the column with the name of the scene 
a1 <- subset(a1, select=1) # class(a1$a): character 
# retrieve an ordered list from the dataframe 
ord_dates <- as.list(as.data.frame(t(a1$a))) # length(ord_dates): 4 (correct) 
# class(odd_dates) # list 

# 2- Create rasters from elements of a list 
for (i in 1:(length(ord_dates))){ 
    # Point to each individual .tif file 
    tif_file <- ord_dates[i] # Problem: accesses only the first item of ord_dates 
    # Make a raster out of it 
    r <- raster(tif_file) # we cant use here a list as an input. Gives error: 
     # Error in .local(x, ...) : list has no "x" 
    # Give it a standardised name (r1,r2,r3, etc) 
    name <- paste("r", 1:length(ord_dates),sep = "") 
    # Write the raster to file 
    writeRaster (r , filename = name,format = "GTiff", overwrite =T) 
} 

나는 또한() 많은 성공없이 lapply 사용하는 것을 시도했다.

r = lapply(ord_dates, raster) 

어떤 개념을 따라야할까요? 나는 행렬을 사용해야한다고 생각하지만 실제로 어떤 이점이 있는지, 어떤 단계에서 필요한지 이해하지 못합니다.

도움이 정말 감사합니다! 사전 ord_dates 가정

답변

0

에서 감사 (전체 경로를하거나 getwd()에있는) 파일 이름의 목록입니다, 당신은 lapply를 사용하여이 목록에 (모든) 기능을 적용 할 수 있습니다. 불행히도 이것을 테스트하지 않았습니다.

convertAllToRaster <- function(tif_file) { 
    r <- raster(tif_file) 
    # Give it a standardised name (r1,r2,r3, etc) 
    name <- paste("r", 1:length(ord_dates),sep = "") 
    # Write the raster to file 
    writeRaster (r , filename = name,format = "GTiff", overwrite =T) 
    message("Eeee, maybe it was written successfully.") 
} 

lapply(ord_dates, FUN = convertAllToRaster) 
+0

로마에 감사드립니다. lapply()를 사용할 때 익숙한 오류가 발생했습니다. (function (classes, fdef, mtable)) 오류 : 서명 ''factor ''에 대해 'raster'함수의 상속 된 메서드를 찾을 수 없습니다. 서명 요소가 만들어진 위치를 이해하지 못합니다. 나는리스트가 클래스 문자이고 인자가 아니라는 것을 확실히함으로써 그것을 고친 것으로 생각했다. – user3127517

+0

당신의리스트 요소는 아마도 인자가 될 것이다. 어떤 경우에는 라인 앞에 (또는) 기능의 시작)을 확인한 다음 코드를 실행하십시오. 함수의 환경을 탐색하고 수동으로 코드를 실행하고 그런 식으로 버그를 추적해야합니다. –

0

요인 및 이름의 문제를 해결 한 후이 코드가 저에게 효과적이었습니다. 나는 당신이 제안한 함수 안에 for 루프를 추가했다. 친절하게 도와 주셔서 대단히 감사합니다 !!

convertAllToRaster <- function(ord_dates) { 
    for (i in 1:(length(ord_dates))){ 
    tif_file <- ord_dates[i] 
    r <- raster(tif_file) 
    # Keep the original name 
    name <- paste(tif_file, ".grd", sep ="") 
    # Write the raster to file 
    writeRaster (r , filename = name,format = "raster", overwrite =T) # in .grd format 
    } 
} 

lapply(ord_dates, FUN = convertAllToRaster)