定义包含文件名的字符串变量,然后在路径(r)中调用此变量

发布于 2025-02-10 02:41:17 字数 504 浏览 1 评论 0原文

我有一个脚本,其中我从.asc文件中读取rasters,例如:

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

现在我想通过字符串变量替换路径(file_a.asc)中的文件名,以便我可以在开始时更改我正在读取的文件代码,而不是读取该特定文件的代码中的任何地方。

因此,例如:

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

当然,这不起作用,但希望它说明了我想做的事情。我真的不知道要朝哪个方向看,也许是“合并”?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

埋情葬爱 2025-02-17 02:41:17

您可以简单地做:

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

You can simply do:

var <- 'file_a.asc'
raster <- brick(paste0("'directory/subdirectory/", var, "'"), varname = 'man')
倒带 2025-02-17 02:41:17

感谢Roland提出的“ Sprintf”功能,正是我想要的。

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

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')             
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文