我如何(最快最好)从字符串的数字部分中删除逗号而不影响字符串中的其余逗号。因此,在下面的示例中,我想从数字部分中删除逗号,但应保留 dog 之后的逗号(是的,我知道 1023455 中的逗号是错误的,但只是在那里抛出了一个角落案例)。
我拥有的:
x <- "I want to see 102,345,5 dogs, but not too soo; it's 3,242 minutes away"
期望的结果:
[1] "I want to see 1023455 dogs, but not too soo; it's 3242 minutes away"
规定:必须在base做,不加包。
先感谢您。
编辑:
谢谢达森、格雷格和德克。您的两个回复都非常有效。我正在玩与 Dason 的回答接近的东西,但括号内有逗号。现在看这甚至没有意义。我在这里对两个响应进行了微基准测试,因为我需要速度(文本数据):
Unit: microseconds
expr min lq median uq max
1 Dason_0to9 14.461 15.395 15.861 16.328 25.191
2 Dason_digit 21.926 23.791 24.258 24.725 65.777
3 Dirk 127.354 128.287 128.754 129.686 154.410
4 Greg_1 18.193 19.126 19.127 19.594 27.990
5 Greg_2 125.021 125.954 126.421 127.353 185.666
+1 给你们所有人。
最佳答案
您可以用数字本身替换任何带有模式(逗号后跟数字)的内容。
x <- "I want to see 102,345,5 dogs, but not too soo; it's 3,242 minutes away"
gsub(",([[:digit:]])", "\\1", x)
#[1] "I want to see 1023455 dogs, but not too soo; it's 3242 minutes away"
#or
gsub(",([0-9])", "\\1", x)
#[1] "I want to see 1023455 dogs, but not too soo; it's 3242 minutes away"
关于regex - 从数字部分字符串中删除逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12126597/