【问题标题】:Replacing decimal (period) in string with two decimals in R用R中的两位小数替换字符串中的小数(句点)
【发布时间】: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)如果有多个数字,它会默默地忽略第二个及以后(在你的情况下可能不是问题)。

标签: r string replace


【解决方案1】:

您可以使用这样的函数来替换第一个句点。

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$number=str_extract(string = words$text,
                           pattern = '\\d+\\.\\d*$')
words %>% dplyr::select(new_text, number)
#                                              new_text number
# 1              I need a number| It is the number 40.6   40.6
# 2 I bet youd like this number| Too bad but it is 52.3   52.3
# 3                 This number is important| It is 1.6    1.6

【讨论】:

    猜你喜欢
    • 2014-03-17
    • 2015-08-25
    • 2016-02-16
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    • 2021-09-18
    相关资源
    最近更新 更多