基于janitor::make_clean_names自定义规则清洗带特殊后缀的R语言字符串向量
自定义janitor列名清洗逻辑实现
清洗规则拆分
落地的规则可拆分为两个独立处理分支,无嵌套逻辑:
- 逐元素判断输入字符串是否以固定值
___specialsuffix结尾 - 匹配到特殊后缀的字符串:仅剥离后缀前的前缀部分执行
janitor::make_clean_names()常规清洗,完成后将原格式的___specialsuffix与清洗后的前缀拼接,全程不改动后缀本身的结构 - 未匹配到特殊后缀的字符串:直接对整段内容执行
janitor::make_clean_names()常规全量清洗
可复用实现代码
# 加载依赖包 library(janitor) library(stringr) # 自定义列名清洗函数 custom_clean_colnames <- function(input_names, special_tail = "___specialsuffix") { # 精确匹配字符串后缀,避免正则转义干扰 suffix_match_flag <- str_ends(input_names, fixed(special_tail)) # 处理带特殊后缀的元素:剥离原后缀、清洗剩余前缀、拼回原格式后缀 suffix_part_clean <- input_names[suffix_match_flag] |> str_remove(fixed(paste0(special_tail, "$"))) |> make_clean_names() |> paste0(special_tail) # 处理无特殊后缀的元素:全量执行常规janitor清洗 normal_part_clean <- input_names[!suffix_match_flag] |> make_clean_names() # 按原向量位置回填结果,保持元素顺序与输入完全一致 output <- input_names output[suffix_match_flag] <- suffix_part_clean output[!suffix_match_flag] <- normal_part_clean return(output) } # 代入示例向量执行测试 vec_of_names <- c( "FIRST_column", "another-column", "ALLCAPS-column", "cOLumn-with___specialsuffix", "blah#4-column", "ANOTHER_EXAMPLE___specialsuffix", "THIS_IS-Misleading_specialsuffix" ) cleaned_output <- custom_clean_colnames(vec_of_names)
运行验证结果
执行上述代码后,得到的清洗输出为:
> cleaned_output [1] "first_column" "another_column" [3] "allcaps_column" "column_with___specialsuffix" [5] "blah_4_column" "another_example___specialsuffix" [7] "this_is_misleading___specialsuffix"
内容的提问来源于stack exchange,提问作者Emman
相关产品推荐
相关产品推荐

