データに対して空間統計関数を実行するには、R data.frame オブジェクトを SpatialPointsDataFrame オブジェクトに変換する必要があります。ただし、何らかの理由で data.frame オブジェクトを SpatialPointsDataFrame に変換すると、変換されたオブジェクトで特定の関数を実行すると、予期しない動作が発生します。
この例では、結果の SpatialPointsDataFrame で head() 関数を実行しようとしています。関数 head() が一部の SpatialPointsDataFrame オブジェクトで失敗するのはなぜですか?
動作を再現するコードは次のとおりです。
例 1、エラーなし:
#beginning of r code
#load S Classes and Methods for Spatial Data package "sp"
library(sp)
#Load an example dataset that contain geographic ccoordinates
data(meuse)
#check the structure of the data, it is a data.frame
str(meuse)
#>'data.frame': 155 obs. of 14 variables: ...
#with coordinates x,y
#Convert the data into a SpatialPointsDataFrame, by function coordinates()
coordinates(meuse) <- c("x", "y")
#check structure, seems ok
str(meuse)
#Check first rows of the data
head(meuse)
#It worked!
#Now create a small own dataset
testgeo <- as.data.frame(cbind(1:10,1:10,1:10))
#set colnames
colnames(testgeo) <- c("x", "y", "myvariable")
#convert to SpatialPointsDataFrame
coordinates(testgeo) <- c("x", "y")
#Seems ok
str(testgeo)
#But try running for instance head()
head(testgeo)
#Resulting output: Error in `[.data.frame`(x@data, i, j, ..., drop = FALSE) :
#undefined columns selected
#end of example code
2 つのサンプル データセットには、理解できない違いがあります。関数 str() は違いを明らかにしませんか?
データセット testgeo で関数 head() が失敗するのはなぜですか?
列を追加するときに head() が機能するのはなぜですか、10が限界のようです:
testgeo <- as.data.frame(cbind(1:10,1:10,1:10,1:10,1:10,1:10,1:10,1:10))
coordinates(testgeo) <- c("V1", "V2")
head(testgeo)