[R] converting a string to a vector without using strsplit and unlink?
Gabor Grothendieck
ggrothendieck at gmail.com
Wed Mar 22 04:58:16 CET 2006
Try this:
x <- "c(1,2)"
eval(parse(text = x))
or
x <- sub("\\{(.*)\\}", "c(\\1)", "{1,2,3,4,5}")
eval(parse(text = x))
or
scan(textConnection(gsub("[{}]", "", "{1,2,3,4,5}")), sep = ",")
On 3/21/06, Tancred Frickey <tancred.frickey at rsbs.anu.edu.au> wrote:
> Hi
>
> I am importing some data from a postgres database and one of the fields
> contains an array of values. This field is in the form "{1,2,3,4,5}" and
> is imported as a character string into "R". I am able to convert the
> string into a vector of numerics using the strsplit and unlist
> functions, but I find that a very inelegant (and slow) solution.
> As an alternative I have coaxed the database into exporting the data in
> the form "c(1,2,3,4,5)" and importing that into R. Unfortunately this is
> also interpreted as one long character string instead of a vector
> containing values. If I edit the corresponding fields in the table with
> the "edit" command and remove the quotes at the beginning and end of the
> line, the data is recognized as a vector of numerics.
>
> Question: Is there any direct or easy way of converting a string
> "c(1,2,3,4,5)" into a vector of values without going through
> strsplit&unlist and/or is there a way to import arrays from postgres
> directly as arrays or vectors and not strings (and thereby avoid all the
> trouble in the first place).
>
>
> Best wishes
>
> Tancred
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>
More information about the R-help
mailing list