在处理多个下划线时将前缀转换为后缀

Convert a prefix to a suffix while dealing with multiple underscores

当变量名可以有多个下划线时,如何将前缀转换为后缀? 有些变量名有 1 个下划线,有些有 3 个下划线。假设前缀始终是字符串的开头到第一个下划线,我如何才能将这些变量名转换为第一个下划线?反之亦然(后缀回到前缀)。

Vars <- c("Low_pq", "High_pq", "Low_total_acid_number", "High_total_acid_number")
Vars

下面的代码准确地反转了带有 1 个下划线的变量名,但在带有多个下划线的变量名上失败了,它们保持不变。

Vars <- str_replace(Vars, "^([^_]*)_([^_]*)$", "\2_\1")
Vars

想要的结果是;

"pq_Low" "pq_High", "total_acid_number_Low" "total_acid_number_High"

您的正则表达式模式略有偏差,您应该在第一个下划线之后使用 .* 来捕获所有剩余内容:

Vars <- str_replace(Vars, "^([^_]*)_(.*)$", "\2_\1")

Demo

在基数 R 中使用 sub

sub('(.*?)_(.*)', '\2_\1', Vars)
#[1] "pq_Low"    "pq_High"  "total_acid_number_Low"  "total_acid_number_High"