我希望将光栅转换为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) )
}
发布于 2019-08-17 14:06:58
在提出问题时,请始终提供一些示例数据。
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")
发布于 2019-08-16 23:34:39
假设你的栅格是“物种”
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))
https://stackoverflow.com/questions/45064450
复制相似问题