从光栅文件中提取特定坐标的数据并在R中合并

时间:2015-05-21 17:33:00

标签: r loops raster

我有网格数据文件(每个文件包含月降雨量,标签为pYYYYMM)https://www.dropbox.com/sh/63z166tjxyu12s5/AAAs3Ccn1zdVoBYMj8Y1o303a?dl=0

library(raster)
files= list.files( ,pattern='*.grd',full.names=TRUE)
df = NULL
for(i in seq_along(files)) {
r2 <- raster(files[i])
# setting the missing values to NA
r2[r2 >= 170141000918782798866653488190622531584.00] <- NA_real_
# Setting the projection
crs(r2) <- "+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +datum=WGS84"
plot(r2)
#Doing this, got me the value for a given point but you will have to manual edit:
d1<- getValuesBlock(r2, row=42, nrows=1, col=26, ncols=1)
# Combine data to get one dataframe 
rbind(df,d1)->df
# then write to a csv file
}

上面的循环在一定程度上适用于我,但这意味着我必须手动更改每个点,然后我也会手动输入日期。

我很恳请一些关于我如何修改我的代码的数据的指导,以获取我感兴趣的纬度和经度的数据。 https://www.dropbox.com/s/3p4u4pyxkyo2q15/latandlong.csv?dl=0

2 个答案:

答案 0 :(得分:0)

这就是你通常会这样做的方式,假设你的所有网格文件排成一行

library(raster)
library(rgdal)
files <- list.files(pattern='.grd$', full.names=TRUE)
s <- stack(files)
# points <- ...

# if your points are lonlat
points <- SpatialPoints(points[, c('longitude', 'latitude')], 
          proj4string=CRS('+proj=longlat +datum=WGS84'))
# and your raster data are not they need to be matched
pts <- spTransform(points, CRS("+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +datum=WGS84")

df <- extract(s, points)
write.csv(df, 'file.csv')

答案 1 :(得分:0)

您的数据位于两个不同的坐标系中,或.grd文件不正确。我看了一下你的实际数据,我的猜测是你的数据来自加拿大,lat和longs都在wgs-1984中,我不确定你的.grd文件是怎么回事。左下角从0,0开始。如果正确提取,您将拥有所有NA值,因为数据不重叠。这是一个数据问题而不是R问题。

library(raster)
library(rgdal)
#get extent of grid file
dat.dir<-'filelocations'
a<-raster(paste0(dat.dir,'/p201307.grd')
extent(a)
#class       : Extent 
#xmin        : -0.5 
#xmax        : 124.5 
#ymin        : -0.5 
#ymax        : 94.5 
#get locs
locs<-read.csv(paste0(dat.dir,'/latandlong.csv'))
head(locs)
#longitude latitude
# 1 -116.8736  60.0334