【发布时间】:2021-05-22 17:49:15
【问题描述】:
我有一个带有如下字符串列的数据集,我正在尝试从字符串中提取数字。我已经实现了对不包含两位小数的观测值的提取。当试图提取两位小数的观察时,我遇到了麻烦。我正在尝试用| 替换第一个小数点,如下所示:
library(stringr)
words=data.frame(text=c('I need a number. It is the number 40.6',
'I bet youd like this number. Too bad but it is 52.3',
'This number is important. It is 1.6'))
words$new_text=str_replace(string = words$text,
pattern = '.',
replacement = '|')
words$new_text
#> [1] "| need a number. It is the number 40.6"
#> [2] "| bet youd like this number. Too bad but it is 52.3"
#> [3] "|his number is important. It is 1.6"
问题出现了,我们可以看到不是第一个. 被替换为| 就像其他字符类型一样,字符串中的第一个字符被替换为|,即我期望这个:
library(stringr)
words=data.frame(text=c('I need a number. It is the number 40.6',
'I bet youd like this number. Too bad but it is 52.3',
'This number is important. It is 1.6'))
words$new_text2=str_replace(string = words$text,
pattern = 'n',
replacement = '|')
words$new_text2
#> [1] "I |eed a number. It is the number 40.6"
#> [2] "I bet youd like this |umber. Too bad but it is 52.3"
#> [3] "This |umber is important. It is 1.6"
编辑:“...尝试提取数字...”,而不是“...尝试提取第二个数字...”
【问题讨论】:
-
秒数是指浮点数的小数部分吗?例如,您期待
c(6, 3, 6)还是c(40.6, 52.3, 1.6)? -
顺便说一句,
.匹配正则表达式中的任何字符。要匹配文字,请在 R 中使用\\.(或在大多数其他语言中使用\.)。 (供参考,stackoverflow.com/a/22944075/3358272) -
哎呀,我的问题不清楚。见编辑。
-
是的,@DaveArmstrong 的
stringr::str_extract是您所需要的,有两个注意事项:(1)它正在返回character,您可能希望在该返回时使用as.numeric; (2)如果有多个数字,它会默默地忽略第二个及以后(在你的情况下可能不是问题)。