I have a Large SpatialGridDataFrame and want to manipulate the content of band1.
In a nested list is the variable name (first entry) and the formula (second entry) included:
name_x <- list(list("Laterite", "RasterData@data$band6_1.60909_SWIR_1 / RasterData@data$band7_2.20125_SWIR_2"),
list("AllIronOxides", "RasterData@data$band4_0.65461_Red / RasterData@data$band2_0.48259_Blue"))
Then I'm reading in a Large SpatialGridDataFrame (S4, tif file):
template <- rgdal::readGDAL(paste(file.path(path_Landsat, atm_file)))
The S4 file template has one variable (band1). In the next step I'm assigning a new variable using the variable name from the list and the content of template (copy template).
assign(paste(name_x[[1]][[1]]), template)
But how is it possible to execute the formula and write the result to this variable?
get(paste(name_x[[1]][[1]])) # access to content of the file
eval(parse(text=name_x[[a]][[2]])) # execute the formula
I'm only able to get access to the content of the variable and to execute the formula. Later I want to put all this into a loop, probably with doParallel and foreach. Something like that:
cl <- makeCluster(parallel::detectCores(all.tests = FALSE, logical = TRUE)-1, outfile="./progress_indices.log") # use #cores-1 for processing
registerDoParallel(cl)
setwd(file.path(path_computedStats))
time_start <- proc.time() #start timer
foreach (a = 1:length(name_x)) %dopar% {
assign(paste(name_x[[a]][[1]]), template) # create variable with name from list name_x
eval(parse(text=name_x[[a]][[2]])) # execute the formula from list name_x
rgdal::writeGDAL(dataset=get(paste0(name_x[[a]][[1]])), fname=file.path(path_computedStats, paste0(substr(atm_file,1,29), sprintf(paste0("_",name_x[[a]][[1]],".tif"), atm_file))),
drivername="GTiff", type="Float32", mvFlag=15000, setStatistics=T)
}
proc.time() - time_start #end time
stopCluster(cl)
edit - Example:
data(meuse.grid)
coordinates(meuse.grid) = c("x", "y")
gridded(meuse.grid) <- TRUE # promote to SpatialPixelsDataFrame
template = as(meuse.grid, "SpatialGridDataFrame") # creates the full grid
rm(meuse.grid)
template[["idist"]] = 1 - template[["dist"]] # assigns new attribute
name_x <- list(list("Laterite", "template@data$part.a / template@data$part.b"),
list("AllIronOxides", "template@data$dist + template@data$part.b"))
for (a in 1:length(name_x)) {
assign(paste(name_x[[a]][[1]]), template) # create variable with name from list name_x
}
eval(parse(text=name_x[[2]][[2]])) # execute formula of nested list
get(paste(name_x[[2]][[1]])) # access to data of created object
AllIronOxides@data$part.a <- eval(parse(text=name_x[[2]][[2]])) # write result of formula to data frame (only real variable name)
get(paste(name_x[[2]][[1]]))@data$part.a <- eval(parse(text=name_x[[2]][[2]])) # not working
Any ideas?