【发布时间】:2017-07-12 17:47:39
【问题描述】:
我希望将栅格转换为 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) )
}
【问题讨论】:
-
您需要将
as.data.frame( rasterToPoints(species) )分配给一个对象,然后将该对象另存为CSV。 -
光栅对象通常可以转换为矩阵。也许尝试这样做,看看矩阵是否可以转换为您需要的数据框。转到此小插图的第 5.4 节:cran.r-project.org/web/packages/raster/vignettes/Raster.pdf