1

for example:

'I want to get 10 apples, 99 bananas and 86 oranges.'

'I want to buy a car'

What I want to do is get the last number in the sentence. The result I m hoping is:

86

NA

How can I make it possible by using R? thanks~

p.s. I just want to catch Arabic numerals

recon
  • 157
  • 9

2 Answers2

5

Using stringi we can use stri_extract_last_regex which will return last matched pattern in the string.

as.numeric(stringi::stri_extract_last_regex(x, "\\d+"))
#[1] 86 NA

data

x <- c('I want to get 10 apples, 99 bananas and 86 oranges', 'I want to buy a car')
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
3

We can use str_extract from stringr which is also based on tidyverse

library(stringr)
as.numeric(sapply(str_extract_all(str1, "\\d+"), tail, 1))
#[1] 86 NA

Or just using only base R

as.numeric(sub(".* (\\d+).*", "\\1", str1))
#[1] 86 NA

If it is a data.frame, we extract the column and update the columns

df1$col1 <- as.numeric(sapply(str_extract_all(df1$col1, "\\d+"), tail, 1))

Also, we can find more resources from this link

data

str1 <- c("I want to get 10 apples, 99 bananas and 86 oranges.",
    "I want to buy a car")
Community
  • 1
  • 1
akrun
  • 874,273
  • 37
  • 540
  • 662