1

How can I convert the string:

a <- "c(\"4\", \"5\", \"7\", \"8\", \"9\", \"10\")" 

to a vector of values: 4,5,7,8,9,10 ?

Jaap
  • 81,064
  • 34
  • 182
  • 193
Dario Federici
  • 1,228
  • 2
  • 18
  • 40
  • 1
    a key question for a situation like this is "why do you have `a` in the first place"/"what are you trying to accomplish that led to `a` as an intermediate step?" there are valid cases to have such an object but they are comparatively rare – MichaelChirico Aug 28 '19 at 05:49
  • Hi Michael, no I don't think it's avoidable and the solution works very well. – Dario Federici Aug 29 '19 at 03:29

1 Answers1

5

The not-so-likeable eval parse can be handy here

as.integer(eval(parse(text = a)))
#[1]  4  5  7  8  9 10

Or maybe you want to keep them as characters as your title indicates.

eval(parse(text = a))
#[1] "4"  "5"  "7"  "8"  "9"  "10"

Based on how complicated the string is you could also extract all the digits from the string.

stringr::str_extract_all(a, "\\d+")[[1]]

Or in base R

regmatches(a, gregexpr("\\d+", a))[[1]]
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213