'How to read multiple files with specific character or number using a loop in R
I have a directory with a bunch of .tif files like: tnt_xxx_2015.tif, tnt_xxx_2016.tif, tnt_xxx_2017.tif......tnt_xxx_2100.tif. 'tnt' is one of the variable names, and for each year "xxx" represents multiple strings. The years are from 2015 to 2100.So I want to find all files that the variable name and year are the same values.I tried to find all files with the variable 'tnt' in same year first:
for (i in 2015:2100)
{
myfiles = Sys.glob("*i.tif")
}
But it doesn't work. It won't accept wildcards; it needs an exact match on the file name. Sys.glob("2015.tif")
runs successfully.
Any ideas?
Solution 1:[1]
How about:
for(I in 2015:2100){
myfiles <- list.files(pattern=paste0(i, ".tif$"))
}
This replicates your code above, but will overwrite myfiles
each time through the loop. If you want to just grab all the files in one vector, you could do the following:
myfiles <- NULL
for(I in 2015:2100){
myfiles <- c(myfiles, list.files(pattern=paste0(i, ".tif$")))
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | DaveArmstrong |