0

I have 14 raster files in Tiff format and I want to read values of a series of pixels (same file location). However, when I ran the R code, the expected results did not show up. Could you tell me why?

#set working directory#
path <- 'E:/TSL_VCF/Tiffs'
setwd(path)
#list tiff files in the working directory#
list.files(path, pattern = 'tif')
#count the number of tiff files#
mylist <- list.files(path, pattern = 'tif')
mylength <- length(mylist)
#get values for certain "location"#
for (i in 1:mylength){
    myraster <- raster(mylist[i])
    mymatrix <- as.matrix(myraster)
    mymatrix[1,771]
}
jrbedard
  • 3,662
  • 5
  • 30
  • 34
sherryL
  • 13
  • 6

2 Answers2

2

results are not printed because the instruction

mymatrix[1,771]

is inside the "for" loop. This:

    #set working directory#
path <- 'E:/TSL_VCF/Tiffs'
setwd(path)
#list tiff files in the working directory#
list.files(path, pattern = 'tif')
#count the number of tiff files#
mylist <- list.files(path, pattern = 'tif')
mylength <- length(mylist)
#get values for certain "location"#
for (i in 1:mylength){
myraster <- raster(mylist[i])
mymatrix <- as.matrix(myraster)
print(mymatrix[1,771])
}

should work.

However, it won't store your resulting array anywhere but on the screen. I'd suggest you to have a look at the extract function of the raster package for a better solution. If you build a rasterstack in advance using something like:

mystack <- stack(mylist)

you can also avoid looping over the files and just do something like:

result <- extract(mystack, as.matrix(c(1,771), nrow = 1))

, and you should get the results in the "result" variable

HTH,

Lorenzo

HTH,

Lorenzo

lbusett
  • 5,801
  • 2
  • 24
  • 47
1

You need to explicitly call print if you want R to print stuff in a loop. For example:

m = rnorm(10)
for (i in 1:10) m[i] # doesn't print
for (i in 1:10) print(m[i]) # print
Vandenman
  • 3,046
  • 20
  • 33