0

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'?

1
  • 1
    help("sprintf") Commented Jun 22, 2022 at 11:00

2 Answers 2

1

You can simply do:

var <- 'file_a.asc'
raster <- brick(paste0("'directory/subdirectory/", var, "'"), varname = 'man')
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this also works - though I feel the solution with 'sprintf' may be a bit more elegant.
0

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')             

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.