Skip to content
Prev 19502 / 29559 Next

Error in SpatialPointsDataFrame(...,match.ID=TRUE)?

I am trying to figure out if I'm missing something very obvious, or if
I came across a potentially serious bug.  I'm using examples from
"Applied Spatial Data Analysis with R" to create a
SpatialPointsDataFrame from the (attached) text file which is from
http://www.asdar-book.org/data2ed.php?chapter=1

The issue I'm having is in the creation of
"CRAN_SpatialPointsDataFrame2" which uses a re-ordered dataframe, but
continues to have the same rownames.  You'll see from the final step
that the coordinates are no longer "in sync" (joined properly) to the
data frame.

Ideas?

###

input_file <- "CRAN051001a.txt" # Attached to this message or from
http://www.asdar-book.org/data2ed.php?chapter=1

# import the file
CRAN_df <- read.table(cran_file,header=TRUE)

# Create a coordinate matrix:
CRAN_mat <- cbind(CRAN_df$long, CRAN_df$lat)

# Add rownames:
row.names(CRAN_mat) <- 1:nrow(CRAN_mat)

# Define a CRS:
CRAN_CRS <- CRS("+proj=longlat +ellps=WGS84")

# Create SpatialPointsDataFrame:
CRAN_SpatialPointsDataFrame1 <-
SpatialPointsDataFrame(coords=CRAN_mat,data=CRAN_df,
proj4string=CRAN_CRS,match.ID=TRUE)

# SpatialPoints coords match the dataframe long and lat:
CRAN_SpatialPointsDataFrame1[1,]

# Reorder the dataframe:
s <- sample(nrow(CRAN_df))
CRAN_df_reordered <- CRAN_df[s,]
rownames(CRAN_df_reordered)
rownames(CRAN_df_reordered["1",])

# Now join using match.ID=TRUE:
CRAN_SpatialPointsDataFrame2 <-
SpatialPointsDataFrame(coords=CRAN_mat,data=CRAN_df_reordered,
proj4string=CRAN_CRS,match.ID=TRUE)
CRAN_SpatialPointsDataFrame2["1",]
# Not matching!