【问题标题】: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将data.frames列表中data.frames的列名分配给R中data.frames列表中的其他(空间)data.frames
【发布时间】:2015-09-14 16:17:55
【问题描述】:

我有一个 data.frames 列表和一个 spatial.data.frames 列表,它们的列数和名称都相同。现在我已经更改了存储在 data.frames 列表中的 (Normal)data.frames 中的一些列名,并希望将这些更改写入存储在另一个列表 (Spatial)data.frames 中的 data.frames 中。

我怎样才能存档这样的东西?

一些例子:

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)

然后在 data.frames 中更改了一些列名。 一个 data.frames 列表中的列名应该写成另一个 (Spatial)data.frames 列表的列名。

到目前为止我尝试的是:

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

}

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

这个函数设法读出不同data.frames的列名并将它们保存在相应的名称下。但现在我不知道如何继续或解决这个问题。

【问题讨论】:

    标签: r function dataframe row


    【解决方案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
    

    【讨论】:

    • 非常感谢您的代码工作得很好!好吧,我想我可能不得不学习如何使用 return()...
    猜你喜欢
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 2011-08-19
    相关资源
    最近更新 更多