1

I have a tiff file having 3 bands R, G, B. I used the following program in R to obtain the pixel values for each band separately.

r<- raster("lena.tiff", band = 1)
writeRaster(r, filename = "lenadd.asc", format = "ascii", datatype= 'INT4U')

It gave me an ascii file containing the pixel values for R band. Similarly, by changing the band value to 2 and 3, I can get the other two files. However, I want to export the data in excel format. But I suppose, writeRaster command doesn't support xlsx format. So, can someone please suggest me any alternative of writeRaster command so that I can export my RGB data in excel format?

I am new to R so pardon me if the question is too trivial.

Edited :

class : RasterLayer

band : 1 (of 3 bands)

dimensions : 512, 512, 262144 (nrow, ncol, ncell)

resolution : 1, 1 (x, y)

extent : 0, 512, 0, 512 (xmin, xmax, ymin, ymax)

coord. ref. : NA

data source : C:\Users\lenovo\Documents\lena.tiff

names : lena

values : 0, 255 (min, max)

2
  • You should probably explain a bit more how you want the data formatted i Excel - do you want the data laid out in a grid, with a new sheet for each lf the channels? Or as a single sheet with five columns - row number, column number, R, G, B values?
    – Spacedman
    Jun 19, 2017 at 15:15
  • @Spacedman I want the data laid out in a grid with a new sheet for each of the channels. Jun 19, 2017 at 15:47

1 Answer 1

1

Here is a function that uses raster and xlsx packages to write a multi-band raster to an Excel spreadsheet, one band per sheet, in a gridded format:

stack_to_xlsx <- function(rs, filename){
    w = createWorkbook()
    for(i in 1:nlayers(rs)){
        cs = createSheet(w, sheetName = paste0("Band-",i))
        dr = raster::as.data.frame(raster::as.matrix(raster(rs,i)))
        addDataFrame(
            dr,
            cs
            )
    }
    saveWorkbook(w, filename)
}

And here's a usage:

Use stack to read in all the bands:

> rs = stack("./preston.tiff")

This is quite a large tiff so I crop it down a bit:

> rsc = stack(crop(rs, extent(350172.7, 351308.5, 429508.1, 430840 )))
> dim(rsc)
[1] 118 100   4
> stack_to_xlsx(rsc, "crop.xls")
> 

Now open crop.xls in Excel (Or OpenOffice, that also works).

3
  • The program runs but there isn't any file exported. Jun 19, 2017 at 16:50
  • How did you load the tiff? What dimension was it? How did you run the stack_to_xls function? What exactly did you type?
    – Spacedman
    Jun 19, 2017 at 16:53
  • sorry, got it.. Jun 19, 2017 at 16:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.