Reading spaces in R

I have this line 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 have to read numbers into a vector. Now I could find the same topics 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 fills in the numbers, as you can see above. I think the problem is expressing regular expressions, but it seems that I cannot get it right, and in fact I have no idea.

I appreciate any comments.

+6
source share
4 answers

If you still want to use your path:

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

and get the numbers:

 as.numeric(unlist(str_extract_all(numbers, "[\\.0-9e-]+"))) 
+4
source

You can 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 
+7
source

A bit dirty, but this should do the trick: as.numeric(unlist(strsplit(numbers, "\\s+")))

Run the line inside out to see what happens, strsplit breaks into spaces and returns a list, unlist makes it a character vector, and as.numeric converts to a number number, leaving you with a number vector.

+2
source
 as.numeric(strsplit(numbers,split=" +")[[1]])->numbers 

( " +" means one or more spaces.)

+1
source

Source: https://habr.com/ru/post/919590/


All Articles