Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R、 在不影响其他值的情况下替换值中的字符_R_Regex_Substitution - Fatal编程技术网

R、 在不影响其他值的情况下替换值中的字符

R、 在不影响其他值的情况下替换值中的字符,r,regex,substitution,R,Regex,Substitution,在R中,我有一个包含数字的字符向量,例如: a <- c("1", "1.5", "-2", "3-4.5", "-1", "5-7.5", "3") a这里有一种方法: a <- c("1", "1.5", "-2", "3$4.5", "-1", "5$7.5", "3") gsub("([^-]+)(-)(.+)", "\\1$\\3", a) ## [1] "1" "1.5" "-2" "3$4.5" "-1" "5$7.5" "3"

在R中,我有一个包含数字的字符向量,例如:

a <- c("1", "1.5", "-2", "3-4.5", "-1", "5-7.5", "3")
a这里有一种方法:

a <- c("1", "1.5", "-2", "3$4.5", "-1", "5$7.5", "3")

gsub("([^-]+)(-)(.+)", "\\1$\\3", a)

## [1] "1"     "1.5"   "-2"    "3$4.5" "-1"    "5$7.5" "3"    

a我们也可以使用regex lookarounds

sub('(?<=\\d)-(?=\\d)', '$', a, perl=TRUE)
#[1] "1"     "1.5"   "-2"    "3$4.5" "-1"    "5$7.5" "3"  

sub(“(?可能类似于
sub(“(\\d)-(\\d)”,“\\1$\\2”,a)
你是我的好朋友。尽管我必须修改第一个参数以接受实数而不是数字。
sub('(?<=\\d)-(?=\\d)', '$', a, perl=TRUE)
#[1] "1"     "1.5"   "-2"    "3$4.5" "-1"    "5$7.5" "3"