R apply raster function to a list of characters

左心房为你撑大大i 提交于 2019-12-12 01:09:12

问题


I started recently to work with R so this question has probably a simple solution. I have some .tif satellite images from different scenes. I can create a test raster brick with it but the process needs to be automatised because of the huge amount of files. Therefore I have been trying to create a function to read the list of .tif files and to output a list of rasters. You can find here below the code I have been using:

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

I have also tried to use lapply() without much success.

r = lapply(ord_dates, raster)

Can you give me an advice on what concept to follow? I am guessing I should be using matrices but I don't really understand which are their advantages here or in what step they are required.

Any help is really appreciated! Thanks in advance


回答1:


Assuming ord_dates is a list of file names (that have full path or are in your getwd()), you can apply a (any) function to this list using lapply. I haven't tested this, unfortunately.

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)



回答2:


After solving the issues with factors and with the name, this is the code that worked for me. I added a for loop also inside the function you proposed, Roman. Thankyou very much for your kind help!!

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)


来源:https://stackoverflow.com/questions/20974677/r-apply-raster-function-to-a-list-of-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!