1
votes

I have a script where I read rasters from .asc files, e.g.:

# Read raster
raster <- brick('directory/subdirectory/file_a.asc', varname = 'man')      

Now I want to replace the filename in the path (file_a.asc) by a string variable, so that I can change the file that I am reading once in the beginning of the code, instead of everywhere in the code where that specific file is read.

So for example:

# Define string variable, containing the name of the file that I want to read
var = 'file_a.asc'
raster <- brick('directory/subdirectory/**var**', varname = 'man')      

Of course this doesn't work, but hopefully it illustrates what I want to do. I don't really know in which direction to look, maybe something with 'merge'?

2
help("sprintf")Roland

2 Answers

1
votes

You can simply do:

var <- 'file_a.asc'
raster <- brick(paste0("'directory/subdirectory/", var, "'"), varname = 'man')
0
votes

Thanks Roland for suggesting the 'sprintf' function, exactly what I was looking for.

var <- 'file_a.asc'
raster <- brick(sprintf('directory/subdirectory/%s', var) , varname = 'man')