Assign column names of data.frames in a list of data.frames to other (Spatial) data.frames in a list of data.frames in R

时间:2015-09-14 16:17:56

标签: r function dataframe row

I have a list of data.frames and a list of spatial.data.frames both have the same number of columns and the same names. Now I have changed some column names in the (Normal)data.frames stored in the list of data.frames and want to write those changes to the data.frames stored in the other list, the (Spatial)data.frames.

How can I archive something like that?

Some example:

require (sp)
mtcars.S <-mtcars
coordinates(mtcars.S) <- c('gear', 'carb')
mtcars.S$coords.x1 <- 12345 
mtcars.S$coords.x2 <- 12345

attitude.S <- attitude
coordinates(attitude.S) <- c('critical', 'advance')
attitude.S$coords.x1 <- 12345 
attitude.S$coords.x2 <- 12345

quakes.S <- quakes
coordinates(quakes.S) <- c('lat', 'long')
quakes.S$coords.x1 <- 12345 
quakes.S$coords.x2 <- 12345


f.Names <- c('mtcars.S','attitude.S','quakes.S')

listofSpatialDF <- mget(f.Names)

b2DF <- function(x) {
  as.data.frame(x)
}

list_DF <- lapply(listofSpatialDF,b2DF)

coordsD <- function(x){
  x[,!names(x) %in% c("coords.x1","coords.x2")]  
}

list_DF <- lapply(list_DF,coordsD)

Then some column names are changed in the data.frames. The column names from one list of data.frames should be written as the column names of the other list of (Spatial)data.frames.

What I tried until now is:

changeCOL <- function(x, y){
  names(y)

}

test<-mapply(changeCOL,x=list_DF,y=listofSpatialDF)

This function managed to read out the column names of the different data.frames and save them under their corresponding name. But now I have no idea how to continue or solve this problem.

1 个答案:

答案 0 :(得分:1)

你有正确的想法 - 我改变了你的功能,现在应该可以了:

changeCOL <- function(x, y){
  names(y) <- names(x)
  return(y)
}

test<-mapply(changeCOL,x=list_DF,y=listofSpatialDF)

# Test to show the names are the same now
names(test[[1]])==names(list_DF[[1]])
[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE