【问题标题】:Replacing column names in list of data.frames by finding pattern R通过查找模式 R 替换 data.frames 列表中的列名
【发布时间】:2019-01-15 13:40:24
【问题描述】:

我有许多具有相似列名的 data.frames 列表,我想通过查找模式并替换整个字符串字符来对其进行标准化。我有以下功能,但由于某种原因,它不能按我的意愿工作。

sampleData1 <- data.frame(id = 1:10, 
                         gender1 = sample(c("Male", "Female"), 10, replace = TRUE),
                         agen = rnorm(10, 40, 10))
sampleData2 <- data.frame(id. = 11:20, 
                          gender22 = sample(c("Male", "Female"), 10, replace = TRUE),
                          age1 = rnorm(10, 44, 10))
sampleData3 <- data.frame(Id = 21:30, 
                          Gnder = sample(c("Male", "Female"), 10, replace = TRUE),
                          age = rnorm(10, 36, 10))
sampleList <- list(sampleData1,sampleData2,sampleData3)

Colnames.change2 <- function(x){
        names(x) <- gsub(".*nder*", "Gender", names(x),ignore.case = TRUE, perl=TRUE)
        names(x) <- gsub(".*Age*", "Age", names(x),ignore.case = TRUE, perl=TRUE)
        names(x) <- gsub(".*id*", "id", names(x),ignore.case = TRUE, perl=TRUE)
        return(x)
}
FinalList <- lapply(sampleList, Colnames.change2)
FinalList

【问题讨论】:

    标签: r lapply gsub string-substitution


    【解决方案1】:

    gsub 模式中缺少一个点;这应该工作 -

    Colnames.change2 <- function(x){
          names(x) <- gsub(".*nder.*", "Gender", names(x),ignore.case = TRUE, perl=TRUE)
          names(x) <- gsub(".*Age.*", "Age", names(x),ignore.case = TRUE, 
    perl=TRUE)
          names(x) <- gsub(".*id.*", "id", names(x),ignore.case = TRUE, perl=TRUE)
          return(x)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-13
      • 1970-01-01
      • 1970-01-01
      • 2019-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多