Search code examples
rfunctionoutputmasknaming

Multiple object manipulation in R


Facing a problem with a function I am trying to set, here. I have the feeling the answer will be pretty simple but I am kinda new to R and stuck,so I would appreciate another opinion. Essentially what I am trying to do is apply a masking function over several raster files, using a single shape-file as an argument and save my outputs in as many objects as the raster files I am working on. For example:

masking <- function(x){
 paste0('x','_45_1',sep='') <- raster::mask(vocc_45_1_rotated,x)
 paste0('x','_45_2',sep='') <- raster::mask(vocc_45_2_rotated,x)
 paste0('x','_45_3',sep='') <- raster::mask(vocc_45_3_rotated,x)
 paste0('x','_85_1',sep='') <- raster::mask(vocc_85_1_rotated,x)
 paste0('x','_85_2',sep='') <- raster::mask(vocc_85_2_rotated,x)
 paste0('x','_85_3',sep='') <- raster::mask(vocc_85_3_new,x)}

Unfortunately I keep on getting an

Error in paste0("x", "_45_1", sep = "") <- raster::mask(vocc_45_1_rotated, :
target of assignment expands to non-language object "

I have seen replies on similar "Error" questions, but nothing that gives me a hint as to what I need to change here.


Solution

  • Dealing with a large number of objects with own names is always tedious and error-prone. Therefore, I suggest to collect all objects of similar structure in a list and to use lapply() to manipulate all objects in the list at once. By this, you can easily build up a processing pipeline.

    To illustrate this, please, see this example:

    # create list of objects
    vocc <- list(vocc_45_1_rotated, 
                 vocc_45_2_rotated, 
                 vocc_45_3_rotated, 
                 vocc_85_1_rotated, 
                 vocc_85_2_rotated,
                 vocc_85_3_new)
    
    # name the objects in the list
    vocc <- setNames(vocc,
                     c("vocc_45_1", 
                       "vocc_45_2", 
                       "vocc_45_3", 
                       "vocc_85_1", 
                       "vocc_85_2",
                       "vocc_85_3"))
    
    # apply raster::mask function on all objects in list,
    # thereby using x as named parameter to function
    # The result is again a list
    masked_vocc <- lapply(vocc, raster::mask, mask = x)
    

    You can retrieve the objects in the list by position

    masked_vocc[[3]]
    

    or by name

    masked_vocc[["vocc_45_3"]]