我data.frame
与下面显示的类似。如何取字符串hours
和hour
与之前的2和1值?
test <- data.frame(value = c('Stick 1 whole clove into center of each diamond. Roast ham 2 hours. Reduce oven temperature to 300F. Continue to roast ham until golden, about 1 hour.'))
> 3
观察:在任何字符串部分都可以找到数字。但是之前hour
或之后hours
。
一种选择是使用正则表达式环顾四周,以在“小时”之前提取数字str_extract_all
,将其转换为numeric
并获取sum
library(stringr)
sum(as.numeric(str_extract_all(test$value, "\\d+(?=\\shour)")[[1]]))
#[1] 3
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句