Import files using key words

2019-07-30 08:03发布

问题:

I would like to import image files using parts of their names. I have 100 .tif images whose names are composed of 3 different elements, say Ai, Bi and Ci in such way: "A1 B1 C1.tif", "A1 B2 C1.tif", "A1 B1 C2.tif", "A2 B1 C1.tif"... I defined Ai, Bi and Ci at the beginning of the code, and want to call the file that contains these 3 elements.

I have tried options that have no chance to be correct, but cannot find anything better:

f = readTiff(Ai Bi Ci)
f = readTiff(Ai, Bi, Ci)
f = readTiff("Ai Bi Ci")

and the same using readImage and file.name. The getwd gives the correct path. Thank you in advance.

回答1:

You can use the paste command to glue strings together.

# for i for A, j for B selection and k for C selection
my.filename <- paste("A", i, " B", j, " C", k, ".tif", sep = "")

so if you wanted to import A1 B2 C2.tif

i <- 1
j <- 2
k <- 2
my.filename <- paste("A", i, " B", j, " C", k, ".tif", sep = "")

Note paste0 defaults to sep = "" so paste0("A", i, " B", j, " C", k, ".tif")

results in my.filename

 1)  "A1 B2 C2.tif"

if you are working with paths then:

my.filename <- paste("A", i, " B", j, " C", k, ".tif", sep = "")
my.path <- getwd() # or set this
readTiff(file.path(my.path, my.filename))

If you want to work through all combinations of i, j, k in loops then you can use file.exists and if it does then import it.

Note: Which package are you using for readTiff? Do not forget to make sure this package is loaded in your script, with library(thispackage) if you are getting "object not found" errors.



标签: r image import