Search code examples
rdigits

Extraction of the two digits before comma from numeric column vector


I have a simulated price series being a column vector. From this, I need to extract my two digits in front of the comma with no rounding, i.e. 87 from the price 1,287.85 and 34 from the price 234.13 and store these in yet another column vector.

Example

str1 <- c("1,287.85", "234.13")

Desired output

str2 <- c("87", "34")

Solution

  • We can use str_extract

    library(stringr)
    as.numeric(str_extract(str1, "\\d{2}(?=\\.)"))
    #[1] 87 34
    

    data

    str1 <- c("1,287.85", "234.13")