通过查找模式R替换data.frames列表中的列名

时间:2018-08-08 10:15:29

标签: r lapply gsub string-substitution

我有许多具有相似列名的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

1 个答案:

答案 0 :(得分: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)
}