0

I have list of many data.frames with similar column names, which I would like to standardise by finding a pattern and replacing the whole string character. I have the following function, but for some reason it doesn't work as I would like it to.

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
MIH
  • 1,083
  • 3
  • 14
  • 26

1 Answers1

1

A dot was missing in the gsub patterns; this should work -

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)
}
Michael Dorman
  • 950
  • 6
  • 8