[GIS] Assigning column names dynamically

attribute-tablegdalrrgdalshapefile

I have an interesting problem:

I need to batchprocess a few files. I do that in a for-loop, where some operations are performed. Later on I want to write the outcome into an existing shapefile which I do like so:

myShapeFile@data <- data.frame(myShapeFile@data,  dynamicColumnName = VALUE)

The dynamicColumnName gets created dynamically – depending what statistic is performed and so on. Meaning: The name is stored in the variable.
So dynamicColumnName could be "2245", in the next iteration of the loop or "0000" or "3334" and so on.

However, the function above does not accept the "characters/integers" stored in the variable. Each column gets named dynamicColumnName.

Any ideas how to not let this happen?

Best Answer

Why not simply track the column position and then use the names assignment eg., names(myShapeFile@data)[5] <- "2245" would assign the value "2245" to the fifth column. Keep in mind that when exported an "X." will be added to the name if it is just a number.

Here is an example where I add 10 columns of random numbers and add associated names using an index for the column name.

library(sp)
data(meuse)
coordinates(meuse) <- ~x+y

for(i in 1:10) {
  meuse@data <- data.frame(meuse@data, runif(nrow(meuse)))
    names(meuse)[length(names(meuse))] <- paste("sim",i,sep=".") 
  }  
names(meuse)