1

Suppose I have the character string

x <-  "   1.1325  -0.9022  -0.1832  -0.5479   0.1236  -0.6556  -1.0599  -0.8881  -0.2136"

and I want to extract the floats to end up with this vector as output:

c(1.1325, -0.9022, -0.1832, -0.5479, 0.1236, -0.6556, -1.0599, -0.8881, -0.2136)

What I managed to achieve is:

na.omit(as.numeric(strsplit(samp, split = "  ")[[1]]))

My question: Is there a more efficient way?

epsilone
  • 745
  • 11
  • 23

1 Answers1

4

We can use scan

scan(text=x, what=numeric(), quiet=TRUE)
#[1]  1.1325 -0.9022 -0.1832 -0.5479  0.1236 -0.6556 -1.0599 -0.8881 -0.2136
akrun
  • 874,273
  • 37
  • 540
  • 662