Home > Blockchain >  Regex - How to extract just the first set of floating numbers from a string - R
Regex - How to extract just the first set of floating numbers from a string - R

Time:08-04

Data: https://pastebin.com/nRsL17BD

My strings look like this: Bipolar 1.389 / Unipolar 6.072 / LAT -17.0

I just need the first set of numbers right after "Bipolar". In this case, I just need 1.389.

A tidyverse answer would be nice but not necessary. Thank you for the help!

CodePudding user response:

This oughta do it:

test <- "Bipolar 1.389 / Unipolar 6.072 / LAT -17.0"
stringr::str_extract(test, "[0-9].[0-9] ")

CodePudding user response:

x <- c("Bipolar 1.389 / Unipolar 6.072 / LAT -17.0", 
       "Bipolar 0.969 / Unipolar 3.678 / LAT -16.0", 
       "Bipolar 0.57 / Unipolar 3.249 / LAT 2.0", 
       "Bipolar 1.011 / Unipolar 3.345 / LAT -11.0", 
       "Bipolar 0.357 / Unipolar 3.573 / LAT -17.0", 
       "Bipolar 1.116 / Unipolar 5.934 / LAT -17.0")

Couple of options -

1 . Extract the first number in the string -

readr::parse_number(x)
#[1] 1.389 0.969 0.570 1.011 0.357 1.116
  1. Base R way to extract the number that comes after "Bipolar"
as.numeric(sub('Bipolar (\\d \\.\\d ).*', '\\1', x))
#[1] 1.389 0.969 0.570 1.011 0.357 1.116
  • Related