Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading space separated numbers in R

I have this string in R:

numbers <- "4 4956  1.00e-09         50.9     1.244 47.1 1.04  5.5     0.499   13.9       0"

and I should read numbers into a vector. Now I could find the same threads for other languages but not for R here. I tried:

library(stringr)
str_extract_all(numbers, "[0-9]+")
[[1]]
[1] "4"    "4956" "1"    "00"   "09"   "50"   "9"    "1"    "244"  "47"   "1"   
[12] "1"    "04"   "5"    "5"    "0"    "499"  "13"   "9"    "0"   

but it messes up the numbers as you can see above. I think the problem is in the regex expression but it seems that I cant get it right and I really have no clue on that.

I appreciate any comment.

like image 766
Ebrahim Jahanshiri Avatar asked Jul 03 '12 14:07

Ebrahim Jahanshiri


2 Answers

You could use scan:

> y <- scan(con <- textConnection(numbers))
Read 11 items
> close(con)
> y
 [1] 4.000e+00 4.956e+03 1.000e-09 5.090e+01 1.244e+00 4.710e+01 1.040e+00
 [8] 5.500e+00 4.990e-01 1.390e+01 0.000e+00
like image 68
Joshua Ulrich Avatar answered Sep 28 '22 20:09

Joshua Ulrich


In case you still want to use your way:

str_extract_all(numbers, "[\\.0-9e-]+")

and to get the numbers:

as.numeric(unlist(str_extract_all(numbers, "[\\.0-9e-]+")))
like image 39
johannes Avatar answered Sep 28 '22 18:09

johannes