2

I would like to find an efficient way to combine certain character + numeric column values in a list of SpatialPolygonsDataFrame objects. Here is reproducible data:

library(maptools)  ## For wrld_simpl
library(sp)

## Example SpatialPolygonsDataFrames (SPDF)
data(wrld_simpl) #polygon of world countries
spdf1 <- wrld_simpl[1:25,] #country subset 1
spdf2 <- wrld_simpl[26:36,] #subset 2
spdf3 <- wrld_simpl[36:50,] #subset 3

#make list of SPDF objects
spdfl<-list()
spdfl[[1]]<-spdf1
spdfl[[2]]<-spdf2
spdfl[[3]]<-spdf3

#view data (attribute table) for one list element
spdfl[[1]]@data

What I would like to do is add another column that is a combination of the FIPS, REGION, and SUBREGION columns, separated by an underscore ('_'). I know how to add+name a new column to each SPDF object in the list as done in the loop below, but I don't know how to get the desired column row entry:

#add new 'unique.id' column to SPDF
for (i in 1:length(spdfl)){
  spdfl[[i]]@data["unique.id"] = ""
}

The row entries for the new unique.id column would be in this format: FIPS_REGION_SUBREGION. For example, for the ATG polygon feature in spdfl[[1]], I would like the 'unique.id' column to have an entry like this:

unique.id
AC_19_29

Please advise on how to do this for all features in the SPDF list.

4

1 回答 1

5
spdfl[[1]]@data$unique.id<- 
paste(spdfl[[1]]@data$FIPS,spdfl[[1]]@data$REGION,spdfl[[1]]@data$SUBREGION,sep="_")

Edit: for your desired looping behavior:

for (i in 1:length(spdfl)){
  spdfl[[i]]@data$unique.id<- 
  paste(spdfl[[i]]@data$FIPS,spdfl[[i]]@data$REGION,
  spdfl[[i]]@data$SUBREGION,sep="_")
  }
于 2018-11-17T01:14:02.043 回答