Marquee
Marquee

Reputation: 135

How can I change string to list in R?

can someone help me ? I need to change string to list. Everything works fine when the inside of the parentheses is not in quotes. However, in my RShiny application, I am forced to use a string in parentheses. But the important thing is that it will not always be just YES and NO. There may be others depending on the dataset.

An example that works

vl = list(Yes = 2, No = 2)

#Output of str(vl):

List of 2
 $ Yes: num 2
 $ No : num 2

I need the same output for

vl = ...("Yes = 2, No = 2")

Upvotes: 0

Views: 89

Answers (1)

Miff
Miff

Reputation: 7941

The eval/parse combination can be used to execute arbitrary strings as code, e.g.

v1 <- eval(parse(text=paste0("list(","Yes = 2, No = 2",")")))
v1
#$Yes
#[1] 2
#
#$No
#[1] 2

str(v1)
#List of 2
# $ Yes: num 2
# $ No : num 2

Upvotes: 2

Related Questions