Search code examples
rpostgresqlvectorplr

convert character string into R integer vector


I receive a character string "{1,0,0,0,0,0}" created as a textual representation of a vector (integer[]) by postgresql and have to cast it into a R integer/numeric vector. Is there any efficient way to convert v into a R representation of a vector? Thanks in advance.

v [1] "{1,0,0,0,0,0}"

class(v) [1] "character"

mode(v) [1] "character"

typeof(v) [1] "character"


Solution

  • If it is positive integer then:

    as.integer(unlist(strsplit("{1,0,0,0,0}", "\\D+"))[-1])
    

    If negative is a possibility:

    as.integer(unlist(strsplit("{1,-3,0,0,0}", "[,{}]"))[-1])