我有一个原子矢量,如:
col_names_to_be_changed <- c("PRODUCTIONDATE", "SPEEDRPM", "PERCENTLOADATCURRENTSPEED", sprintf("SENSOR%02d", 1:18))
我想在单词之间加_
,除了第一个单词(R Style for dataframes from advanced R之后),将它们全部小写。我想要这样的东西:
new_col_names <- c("Production_Date", "Percent_Load_At_Current_Speed", sprintf("Sensor_%02d", 1:18))
假设我的话仅限于此列表:
list_of_words <- c('production', 'speed', 'percent', 'load', 'at', 'current', 'sensor')
我正在考虑使用gsub
的算法,将_
放在上面列表中找到单词的位置,然后将每个单词的第一个字母大写。虽然我可以手动执行此操作,但我想了解如何使用gsub
更好地完成此操作。谢谢。
答案 0 :(得分:2)
您可以获取单词列表并使用look-behind((?<=)
)粘贴它们。我添加了(?=.{2,})
,因为它也会匹配“DATE”中的“AT”,因为“AT”在单词列表中,所以单词列表中的任何内容都需要跟随2个或更多字符用下划线分开。
第二个gsub
只进行大写
list_of_words <- c('production', 'speed', 'percent', 'load', 'at', 'current', 'sensor')
col_names_to_be_changed <- c("PRODUCTIONDATE", "SPEEDRPM", "PERCENTLOADATCURRENTSPEED", sprintf("SENSOR%02d", 1:18))
(pattern <- sprintf('(?i)(?<=%s)(?=.{2,})', paste(list_of_words, collapse = '|')))
# [1] "(?i)(?<=production|speed|percent|load|at|current|sensor)(?=.{2,})"
(split_words <- gsub(pattern, '_', tolower(col_names_to_be_changed), perl = TRUE))
# [1] "production_date" "speed_rpm" "percent_load_at_current_speed"
# [4] "sensor_01" "sensor_02" "sensor_03"
gsub('(?<=^|_)([a-z])', '\\U\\1', split_words, perl = TRUE)
# [1] "Production_Date" "Speed_Rpm" "Percent_Load_At_Current_Speed"
# [4] "Sensor_01" "Sensor_02" "Sensor_03"