library(sp)
data(meuse)
plot(meuse)
slotNames(meuse) #".Data" "names" "row.names" ".S3Class"
coordinates(meuse) <- ~x+y #Add "ID" column to "meuse"
slotNames(meuse) #[1] "data" "coords.nrs" "coords" "bbox" "proj4string"
class(meuse) #[1] "SpatialPointsDataFrame"
names(meuse@data)
#[1] "cadmium" "copper" "lead" "zinc" "elev" "dist" "om" "ffreq" "soil" "lime"
#[11] "landuse" "dist.m"
meuse@data <- data.frame(ID=1:nrow(meuse), meuse@data) #adds an ID field
names(meuse@data)
#[1] "ID" "cadmium" "copper" "lead" "zinc" "elev" "dist" "om" "ffreq" "soil"
#[11] "lime" "landuse" "dist.m"
#Create a data.frame "df.new" with "IDS" (note different name) and "y" columns.
meuse_table.df <- data.frame(IDS=1:nrow(meuse), y=runif(nrow(meuse)))
class(meuse_table.df) #"data.frame"
#Now we can merge "df.new" to "meuse" (@data slot)
meuse <- merge(meuse, meuse_table.df, by.x = "ID", by.y = "IDS")
#create a new file named meuse, consisting of a merge of:
# the meuse spatial points (from the original)
# the dataframe created from the original, using the data.frame command
# BY the field "ID" in the spatialpointsdataframe
# By the field "IDS" in the tabular dataframe (df.new)
head(meuse@data)
# I think the source of unease is that adding an ID field to both files
#is based on them having the same number of rows in the same order.
#in ArcGIS, this would be an unreasonable and dangerous assumption.
#R seems to have some sort of 'innate' key field, based on the order read it.
#This is all great when splitting one file, and merging it back together.
#but what about two files?
#I think it can be done, but it's a three-step process.
#First, merge the polygons. Add an ID field, as above.
#Second, merge the tables (as dataframes), and add ID's. as above.
#Third, attach the merged tables to the merged polygons.
#For it to work, the order of things in the merge (polgyons, dataframe) needs be identfical.