简体   繁体   English

将data.frame列表中的data.frame列名称分配给R中data.frame列表中的其他(空间)data.frames

[英]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

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. 我有一个data.frames列表和一个space.data.frames列表,它们具有相同的列数和相同的名称。 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. 现在,我已经更改了存储在data.frames列表中的(Normal)data.frames中的某些列名称,并希望将这些更改写入存储在另一个列表中的(Spatial)data.frames中的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. 然后,在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. 一个data.frames列表中的列名应被写为(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. 该函数设法读取不同data.frames的列名,并将它们保存在其相应名称下。 But now I have no idea how to continue or solve this problem. 但是现在我不知道如何继续或解决这个问题。

You had the right idea - I changed your function a bit and it should work now: 您的想法正确-我对您的功能做了一些更改,现在应该可以使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM