2016-12-19 30 views
1

我有一個SpatialPoints用3名維對象:卸下第三維中SpatialPointsDataFrame

x <- c(1,1,1,2,2,2,3,3,3) 
y <- c(1,2,3,1,2,3,1,2,3) 
z <- c(1,3,5,2,1,2,1,2,3) 
xyz <- cbind(x,y,z) 
ss <- SpatialPoints(xyz) 
dimensions(ss) 

而一個raster對象:

rr <- raster(matrix(round(runif(49,0,10)),7,7), xmn=0, xmx=4, ymn=0, ymx=4, crs=NA, template=NULL) 

我想使用SpatialPoints對象提取柵格值:

extract(rr,ss) 
#Error in .xyValues(x, coordinates(y), ..., df = df) : 
# xy should have 2 columns only. 
#Found these dimensions: 9, 3 

如果你wa可以看到數據NT:

plot(rr) 
plot(ss, add=T) 

所以問題是,光柵包的extract函數需要一個2維對象SpatialPoints。我的(在我的真實數據)3維。有沒有辦法放棄我的點形狀的第三維?我試過了:

coordinates(ss) <- coordinates(ss)[,-3] 
#Error in `coordinates<-`(`*tmp*`, value = c(1, 1, 1, 2, 2, 2, 3, 3, 3, : 
# setting coordinates cannot be done on Spatial objects, where they have #already been set 

我不想從頭重建我的形狀。

+0

你在找這樣的:SS @ COORDS [1:2] – MLavoie

+0

@MLavois,你說什麼給了我作爲一個矩陣的二維(這與我的座標(ss)[, - 3]')是一樣的,這不是我想要的,我想要一個新的形狀對象,但是隻有2個維度,而不是3個。保持所有其他部分相同(數據,投影等) – Bastien

+1

剛剛覆蓋'coords'插槽:'ss @ coords <-ss @ coords [,1:2]' – rcs

回答

1

只是覆蓋S4對象的coords插槽:

[email protected] <- [email protected][, 1:2] 

我不知道你的SpatialPoints對象是如何創建的,但如果你使用rgdal::readOGR有一個pointDropZ參數(默認FALSE

+0

'pointDropZ'參數也是我不知道的好解決方案。我將使用那個,因爲我使用'readOGR'。謝謝。 – Bastien

0

@rcs回答是好,但這個作品,以及:

ss <- SpatialPoints(coordinates(ss)[,-3]) 

,如果你有一個SpatialPointsDataFrame:

ss <- SpatialPointsDataFrame(coordinates(ss)[,-3], [email protected],proj4string=CRS(proj4string(ss)))