igbobahaushe
igbobahaushe

Reputation: 65

Remove quotes from a character object in R

Suppose you have a character object of the form "c('r1', 'r2', 'r3')"

how can you strip the external quote marks to return c('r1', 'r2', 'r3')

Upvotes: 0

Views: 886

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 270195

Assuming s is as shown below and you want to iterate over three character strings:

s <- "c('r1', 'r2', 'r3')"

rr <- eval(parse(text = s)) ; rr
## [1] "r1" "r2" "r3"

for(r in rr) print(r)  # can use it in a for loop like this
## [1] "r1"
## [1] "r2"
## [1] "r3"

or if what you meant is that r1, r2 and r3 are R variables then using rr from above:

r1 <- 1; r2 <- 2; r3 <- 3
L <- mget(rr)  # list with elements 1, 2 and 3
for(r in L) print(r)
## [1] 1
## [1] 2
## [1] 3

There may be some earlier step you can take to create an object easier to deal with in the first place but that can't be determined from the question as stated.

Upvotes: 2

Related Questions