[R-sig-Geo] Antw: transfer raster values to dataframe

Matteo Mattiuzzi matteo.mattiuzzi at boku.ac.at
Thu Mar 14 22:37:19 CET 2013


Dear Ross,


set.seed(1234)
myPointsSp <- data.frame(x=rnorm(10, mean=1.23347499, sd=0.002),
y=rnorm(10, mean=52.00096, sd=0.002))
coordinates(myPointsSp) <- c('x', 'y')
proj4string(myPointsSp) <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84")

# make raster
myExtent <- extent(myPointsSp)
myRaster <- raster(ext=myExtent, crs="+proj=longlat +ellps=WGS84 +datum=WGS84", ncol=2, nrow=2)

# assign values to raster
myRaster[] <- rnorm(4)



myPointsDf <- as.data.frame(myPointsSp)

# I think a simple extract is what you are looking for:
myPointsDf <- extract(myRaster,myPointsSp)


# Matteo

>>> Ross Ahmed  14.03.13 22.00 Uhr >>>
I need to transfer the values from a raster to a dataframe programatically.
Hopefully code below should explain what I need but let me know if not.

# make spatial points
set.seed(1234)
myPointsSp <- data.frame(x=rnorm(10, mean=1.23347499, sd=0.002),
y=rnorm(10, mean=52.00096, sd=0.002))
coordinates(myPointsSp) <- c('x', 'y')
proj4string(myPointsSp) <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84")

# make raster
myExtent <- extent((bbox(myPointsSp)))
myRaster <- raster(ext=myExtent,crs="+proj=longlat +ellps=WGS84
+datum=WGS84", ncol=2, nrow=2)

# assign values to raster
myRaster[] <- rnorm(4)

# cell number of raster that points fall in
myPointsDf <- as.data.frame(myPointsSp)
myPointsDf$cell.number <- cellFromXY(myRaster, myPointsSp)

# this is what I need - value of cell number transferring to myPointsDf. How
can 
# I do this programatically?
myPointsDf$cell.value <- c(0.3574899,  0.3054585,  0.7327708, 0.7327708,
-1.2390943, 0.3054585,
                           -1.2390943, -1.2390943,  0.3574899, 0.3574899)


Thanks
Ross



    [[alternative HTML version deleted]]

_______________________________________________
R-sig-Geo mailing list
R-sig-Geo at r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo



More information about the R-sig-Geo mailing list