我经常从数据集中的变量/列的不一致命名的协作者获取数据集。我的第一个任务之一是重命名它们,我想在R中完全解决这个问题。
- as.Given <- c("ICUDays","SexCode","MAX_of_MLD","Age.Group")
- underscore_lowercase <- c("icu_days","sex_code","max_of_mld","age_group")
- camelCase <- c("icuDays","sexCode","maxOfMld","ageGroup")
鉴于different opinions about naming conventions和what was proposed in Python的精神,在R中以用户指定的方式从as.Given到underscore_lowercase和/或camelCase有什么方法?
编辑:Also found this related post in R / regex,特别是@rengis的答案。
尝试这个。这些至少在以下示例上工作:
- toUnderscore <- function(x) {
- x2 <- gsub("([A-Za-z])([A-Z])([a-z])","\\1_\\2\\3",x)
- x3 <- gsub(".","_",x2,fixed = TRUE)
- x4 <- gsub("([a-z])([A-Z])","\\1_\\2",x3)
- x5 <- tolower(x4)
- x5
- }
- underscore2camel <- function(x) {
- gsub("_(.)","\\U\\1",x,perl = TRUE)
- }
- #######################################################
- # test
- #######################################################
- u <- toUnderscore(as.Given)
- u
- ## [1] "icu_days" "sex_code" "max_of_mld" "age_group"
- underscore2camel(u)
- ## [1] "icuDays" "sexCode" "maxOfMld" "ageGroup"