在R中的单词模式后获取数字

问题描述 投票:1回答:1

例如,我需要在数据表列中的单词后获取数字:

y = data.table(status =c( "client rating 01 approved", "John Rating: 2 reproved", "Customer rating9") )

然后,我需要获得等级一词后的数字,并使用该等级号创建一个新列,在示例中,它应为:rating = c(1,2,9)

[如何考虑评级后的变化,例如:,双倍空格,无空格?

r regex data.table match text-extraction
1个回答
0
投票

我们可以使用sub来捕获“等级”之后的数字(\\d+),包括字符:或空格,并用numeric转换为as.numeric

library(data.table)
y[, num := as.numeric(sub(".*rating[^0-9]*(\\d+)\\b.*", "\\1",
         status, ignore.case = TRUE))]
y
#                      status num
#1: client rating 01 approved   1
#2:   John Rating: 2 reproved   2
#3:          Customer rating9   9
© www.soinside.com 2019 - 2024. All rights reserved.