在R中将栅格转换为csv

时间:2017-07-12 17:47:40

标签: r csv dataframe r-raster

我希望将栅格转换为csv文件。我试图将光栅转换为一个文件上的数据帧,只是为了查看它是否有效。我尝试过使用:

as.data.frame( rasterToPoints(species) )

但是当我尝试编写"物种"到csv:

Error in as.data.frame.default(x[[i]], optional = TRUE) : 
cannot coerce class "structure("RasterLayer", package = "raster")"   to a data.frame

这是我的代码(我需要将多个栅格转换为csv(参见循环))

#start loop
file.names <- dir(path, pattern=".csv")

for(i in 1:length(file.names)){
  file<- read.csv(file.name[i], header = TRUE, stringsAsFactors=FALSE)

#subsetting each file and renaming column header names
sub.file<-subset(file, select = c('Matched.Scientific.Name',  'Vernacular.Name...matched', 'Latitude...processed', 'Longitude...processed'))
names(sub.file) <- c('species', 'name', 'Lat','Lon')

#turn into a SpatialPointsDataFrame 
coordinates(sub.file) <- ~ Lon + Lat 
proj4string(sub.file) <- '+init=EPSG:4326'
plot(sub.file, axes=TRUE)

#converting to BNG
sub.file.BNG <- spTransform(sub.file, '+init=EPSG:27700')
plot(sub.file.BNG, axes=TRUE)

#creating template raster
template <- raster(xmn=400000, xmx=600000, ymn=200000, ymx=800000,  res=25000, crs='+init=EPSG:27700')

#point data > presence grid
species <- rasterize(sub.file.BNG, template, field=1)
plot(species)

# UK wide
template <- raster(xmn=-200000, xmx=700000, ymn=0, ymx=1250000, res=25000, crs='+init=EPSG:27700')

# use that to turn species point data into a presence grid
species <- rasterize(sub.file, template, field=1)
plot(species)

#converting a raster>dataframe>csv?????
as.data.frame( rasterToPoints(species) )
}

2 个答案:

答案 0 :(得分:1)

在提问时总是提供一些示例数据。

library(raster)
f <- system.file("external/test.grd", package="raster")
r <- raster(f)

获取单元格值

x <- as.data.frame(r)
head(x, 2)
#  test
#1   NA
#2   NA

要获取单元格坐标和值,仅适用于非NA单元格

x <- rasterToPoints(r) 
head(x, 2)
#         x      y    test
#[1,] 181180 333740 633.686
#[2,] 181140 333700 712.545

要获取单元格的坐标和值,仅适用于所有单元格(包括NA)

x <- cbind(coordinates(r), v=values(r))
head(x, 2)
#          x      y  v
#[1,] 178420 333980 NA
#[2,] 178460 333980 NA

无论您选择哪种方式,都可以

write.csv(x, "test.csv")

您犯的错误是您没有将as.data.frame的结果分配给变量,然后尝试使用write.csv编写RasterLayer。这是一个错误,您得到

write.csv(r)
#Error in as.data.frame.default(x[[i]], optional = TRUE) : 
# cannot coerce class ‘structure("RasterLayer", package = "raster")’ to a 
# data.frame

顺便说一句,如果您有多个栅格,则可能要先将它们合并

s <- stack(r, r, r)
x <- rasterToPoints(s) 
head(x, 2)
#          x      y  test.1  test.2  test.3
#[1,] 181180 333740 633.686 633.686 633.686
#[2,] 181140 333700 712.545 712.545 712.545
write.csv(x, "test.csv")

答案 1 :(得分:0)

假设您的栅格是“物种”

 species<- raster("C:/.../species.tif")

要执行此转换,必须获取每个像素的值:X坐标(1),Y坐标(2)和每个像元自己的值(3)。

 # don't run these lines
 #(1) = coordinates (species) [, 1]
 #(2) = coordinates (species) [, 2]
 #(3) = values (species)

有了这些表达式,我们可以将它们添加到数据框中,如下所示

dat<- data.frame("X"=coordinates(species)[,1],"Y"=coordinates(species) 
[,2],"Values"=values(species))