我希望将栅格转换为 csv 文件。我尝试将一个文件上的栅格转换为数据帧,只是为了看看它是否有效。我尝试过使用:
as.data.frame( rasterToPoints(species) )
Run Code Online (Sandbox Code Playgroud)
但是当我尝试将“species”写入 csv 时出现错误:
Error in as.data.frame.default(x[[i]], optional = TRUE) :
cannot coerce class "structure("RasterLayer", package = "raster")" to a data.frame
Run Code Online (Sandbox Code Playgroud)
这是我的代码(我需要将多个栅格转换为 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) )
}
Run Code Online (Sandbox Code Playgroud)
提问时始终提供一些示例数据。
\n\nlibrary(raster)\nf <- system.file("external/test.grd", package="raster")\nr <- raster(f)\nRun Code Online (Sandbox Code Playgroud)\n\n获取单元格值
\n\nx <- as.data.frame(r)\nhead(x, 2)\n# test\n#1 NA\n#2 NA\nRun Code Online (Sandbox Code Playgroud)\n\n获取单元格坐标和值,仅适用于非 NA 的单元格
\n\nx <- rasterToPoints(r) \nhead(x, 2)\n# x y test\n#[1,] 181180 333740 633.686\n#[2,] 181140 333700 712.545\nRun Code Online (Sandbox Code Playgroud)\n\n获取单元格坐标和值,仅适用于所有单元格(包括 NA)
\n\nx <- cbind(coordinates(r), v=values(r))\nhead(x, 2)\n# x y v\n#[1,] 178420 333980 NA\n#[2,] 178460 333980 NA\nRun Code Online (Sandbox Code Playgroud)\n\n无论您选择哪一个,您都可以执行以下操作
\n\nwrite.csv(x, "test.csv")\nRun Code Online (Sandbox Code Playgroud)\n\n您犯的错误是您没有将 的结果分配as.data.frame给变量,然后尝试用 编写RasterLayer write.csv。这是一个错误,你会得到
write.csv(r)\n#Error in as.data.frame.default(x[[i]], optional = TRUE) : \n# cannot coerce class \xe2\x80\x98structure("RasterLayer", package = "raster")\xe2\x80\x99 to a \n# data.frame\nRun Code Online (Sandbox Code Playgroud)\n\n顺便说一句,如果您有多个栅格,您可能需要先将它们组合起来
\n\ns <- stack(r, r, r)\nx <- rasterToPoints(s) \nhead(x, 2)\n# x y test.1 test.2 test.3\n#[1,] 181180 333740 633.686 633.686 633.686\n#[2,] 181140 333700 712.545 712.545 712.545\nwrite.csv(x, "test.csv")\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
7370 次 |
| 最近记录: |