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
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)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.