Home > Blockchain >  Parsing text in R (e.g., "[1,2,3]")
Parsing text in R (e.g., "[1,2,3]")

Time:12-15

I would like to convert a string like this "[1,2,3]" into a vector like this c(1,2,3) in R. Any suggestions?

Thank you!

I was only able to get rid of the quotes and brackets but I have difficulty converting the resulting character "1,2,3" into a numeric vector.

CodePudding user response:

An option is to change the [] to () and use eval/parse

eval(parse(text = paste0('c', chartr("[]", "()", "[1,2,3]" ))))
#[1] 1 2 3

Or a package solution will be using jsonlite

library(jsonlite)
fromJSON("[1,2,3]")
[1] 1 2 3

CodePudding user response:

Another option is first removing [ and ] with gsub and after that split the number with strplit by comma like this:

string = "[1,2,3]"
gsub('\\[|\\]', '', string)           
#> [1] "1,2,3"
as.numeric(unlist(strsplit(gsub('\\[|\\]', '', string), ',')))
#> [1] 1 2 3

Created on 2022-12-14 with reprex v2.0.2

  • Related