我想对空间网格数据框进行简单的操作。考虑我需要知道每个空间点(此处为行)的每列的总和。不幸的是,我无法使用sum或rowSums函数来做到这一点。你能帮帮我怎么做吗?我搜索了很多,但实际上并没有看到任何类似的情况。
我的数据摘要是:
FLint
Object of class SpatialGridDataFrame
Object of class SpatialGrid
Grid topology:
cellcentre.offset cellsize cells.dim
x 582228.8 9.071439 568
y 4505538.0 9.071439 445
SpatialPoints:
x y
[1,] 582228.8 4509566
[2,] 582237.9 4509566
....
Data summary:
Deterministic sim001 sim002
Min. :1 Min. :1 Min. :1
1st Qu.:1 1st Qu.:1 1st Qu.:1
Median :1 Median :1 Median :1
Mean :1 Mean :1 Mean :1
3rd Qu.:1 3rd Qu.:1 3rd Qu.:1
Max. :1 Max. :1 Max. :1
NA's :220354 NA's :220354 NA's :220354
在这里,我尝试了很多例子,例如最后两列:
y2 <- rowSums (FLint[,2:3], na.rm = TRUE, dims = 1)
Error in base::rowSums(x, na.rm = na.rm, dims = dims, ...) :
'x' must be an array of at least two dimensions
答案 0 :(得分:0)
我对您是否需要rowSums()
或colSums()
感到有些困惑,但两者都会以相同的方式使用:
您需要在S4对象的rowSums()
位置上调用data
这是一个玩具示例
library(sp)
## data taken from ?SpatialGridDataFrame
data(meuse.grid) # only the non-missing valued cells
coordinates(meuse.grid) = c("x", "y") # promote to SpatialPointsDataFrame
gridded(meuse.grid) <- TRUE # promote to SpatialPixelsDataFrame
x = as(meuse.grid, "SpatialGridDataFrame")
## the data is contained in '@data'
rowSums(x@data[, c("part.a", "part.b")], na.rm = T)
因此,在您的示例中,我认为您想要
rowSums(Flint@data[, 2:3])
如果查看结构
,您可以看到数据的位置str(x)
Formal class 'SpatialGridDataFrame' [package "sp"] with 4 slots
..@ data :'data.frame': 8112 obs. of 5 variables:
.. ..$ part.a: num [1:8112] NA NA NA NA NA NA NA NA NA NA ...
.. ..$ part.b: num [1:8112] NA NA NA NA NA NA NA NA NA NA ...
.. ..$ dist : num [1:8112] NA NA NA NA NA NA NA NA NA NA ...
.. ..$ soil : Factor w/ 3 levels "1","2","3": NA NA NA NA NA NA NA NA NA NA ...
.. ..$ ffreq : Factor w/ 3 levels "1","2","3": NA NA NA NA NA NA NA NA NA NA ...
..@ grid :Formal class 'GridTopology' [package "sp"] with 3 slots
.. .. ..@ cellcentre.offset: Named num [1:2] 178460 329620
.. .. .. ..- attr(*, "names")= chr [1:2] "x" "y"
.. .. ..@ cellsize : Named num [1:2] 40 40
.. .. .. ..- attr(*, "names")= chr [1:2] "x" "y"
.. .. ..@ cells.dim : Named int [1:2] 78 104
.. .. .. ..- attr(*, "names")= chr [1:2] "x" "y"
..@ bbox : num [1:2, 1:2] 178440 329600 181560 333760
.. ..- attr(*, "dimnames")=List of 2
.. .. ..$ : chr [1:2] "x" "y"
.. .. ..$ : chr [1:2] "min" "max"
..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
.. .. ..@ projargs: chr NA