我有一長串要在 R 中上傳以合并它們的光柵檔案。這是我目錄中的檔案示例
dir()
[1] "example_raster_a.tif" "example_raster_b.tif" "example_raster_c.tif" "example_raster_1.tif"
[5] "example_raster_2.tif" "example_raster_3.tif"
我要選擇的檔案全部以數值結尾,但我不知道該怎么做
這可能是一個微不足道的問題,但我不習慣使用字串函式,也沒有設法在網上找到資訊
uj5u.com熱心網友回復:
一個可能的解決方案:
strings <- c("example_raster_a.tif","example_raster_b.tif","example_raster_c.tif","example_raster_1.tif","example_raster_2.tif","example_raster_3.tif")
strings[grepl("\\d\\.tif", strings)]
#> [1] "example_raster_1.tif" "example_raster_2.tif" "example_raster_3.tif"
uj5u.com熱心網友回復:
您可以使用正則運算式:https ://stat.ethz.ch/R-manual/R-devel/library/base/html/regex.html來選擇相關檔案。
grep("[0-9] \\.tif", dir(), value = TRUE)
uj5u.com熱心網友回復:
您可以使用Sys.glob匹配某些檔案模式:
print(Sys.glob('./*[0-9].tif'))
輸出:
[1] "./test_1.tif" "./test_2.tif" "./test_3.tif"
所有檔案:
print(Sys.glob('*.tif'))
輸出:
[1] "test_1.tif" "test_2.tif" "test_3.tif" "test_a.tif" "test_b.tif"
[6] "test_c.tif"
不如 grep 強大(無法匹配更復雜的模式,例如匹配一行中的任意數量的數字),但更簡單(也許)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/488582.html
