Tokenizing Strings

Dear All,

Curious enough, I came across tokenizing strings today which I am not familiar of. It seems quite simple with character and so I tried using numeric characters but then I cant get my way through it.

Please, how do I tokenize this line of code and then make it numeric?

x <- "1 4 3.5 6 0.1 9 11"

Thanks

x <- "1 4 3.5 6 0.1 9 11"
as.numeric(unlist(strsplit(x, ' ')))
[1]  1.0  4.0  3.5  6.0  0.1  9.0 11.0
3 Likes

another solution using stringr :package: that helps manipulate string. Useful if you are already working with the tidyverse loaded, but exactly the same as the previous one.

x <- "1 4 3.5 6 0.1 9 11"
library(stringr)
as.numeric(str_split(x, " ")[[1]])
#> [1]  1.0  4.0  3.5  6.0  0.1  9.0 11.0

Created on 2018-07-20 by the reprex package (v0.2.0).

2 Likes

Thanks very much. This is helpful

1 Like

Thanks very much. It helps

You are welcome - Remember to mark the solution :slightly_smiling_face:

1 Like