Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raster to table using r

Tags:

r

raster

I want to convert a raster to a table in R using the command head, I am using a .bil downloaded from Worldclim site to get the information. I would like to have the temperature in a table with coordinates(latitude,longitude). How do I do that?

When I do this:

temperature1<-raster("tmean_8.bil")
head(temperature1)

I get the result like this:

     1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19
1  260 259 258 258 259 258 258 257 257 256 255 254 255 255 254 252 251 252 250
2  259 258 258 257 258 257 257 257 257 256 256 257 251 251 252 251 255 255 252
3  260 259 258 258 258 258 256 257 257 255 252 253 254 252 253 251 251 253 253
4  258 257 258 258 256 254 258 258 257 257 255 256 255 257 254 252 255 255 255
....
like image 218
eloso Avatar asked Oct 27 '25 06:10

eloso


2 Answers

Try this

as.data.frame(temperature, xy = TRUE)
like image 146
mdsumner Avatar answered Oct 29 '25 20:10

mdsumner


Without downloading a large file from http://www.worldclim.org/current, this is pretty much a "wide to long" problem that melt should be able to handle. The following snippet makes a raster object from a matrix, then converts it to a data frame and uses melt to get it into the x/y pairs you're looking for.

library(reshape2)
library(raster)

ras <- raster(as.matrix(read.table(text = "0 0 0 0 0 0 0 0 0 0
41 10 2 0 0 0 0 0 0 0
75 36 20 9 4 2 1 0 0 0
91 65 47 31 20 13 8 5 3 2
97 78 64 47 35 25 18 12 8 5
99 88 76 63 50 39 29 22 16 11
99 93 85 74 63 52 42 32 25 19
99 96 91 83 73 64 53 44 35 28
99 98 94 88 81 72 64 54 46 37
99 98 96 92 87 80 72 64 55 47")))

# convert raster to a data frame
ras.df <- as.data.frame(as.matrix(ras))

# setting 'x' column names
colnames(ras.df) <- 1:10

# creating 'y' column names
ras.df$y <- 1:10

# wide to long conversion
ras.df <- melt(ras.df, id.vars="y")

# better names
colnames(ras.df) <- c("y", "x", "value")

head(ras)

##     1  2  3  4  5  6  7  8  9 10
## 1   0  0  0  0  0  0  0  0  0  0
## 2  41 10  2  0  0  0  0  0  0  0
## 3  75 36 20  9  4  2  1  0  0  0
## 4  91 65 47 31 20 13  8  5  3  2
## 5  97 78 64 47 35 25 18 12  8  5
## 6  99 88 76 63 50 39 29 22 16 11
## 7  99 93 85 74 63 52 42 32 25 19
## 8  99 96 91 83 73 64 53 44 35 28
## 9  99 98 94 88 81 72 64 54 46 37
## 10 99 98 96 92 87 80 72 64 55 47


head(ras.df)

##   y x value
## 1 1 1     0
## 2 2 1    41
## 3 3 1    75
## 4 4 1    91
## 5 5 1    97
## 6 6 1    99
like image 30
hrbrmstr Avatar answered Oct 29 '25 19:10

hrbrmstr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!