this_name_here
this_name_here

Reputation: 1

R - Extracting a reference object from a string?

In R, I have a list that looks something like this:

x <- list(`1`=1, `2`=2, `3`=3)

and a variable like this:

a = '`1`'

and I need to somehow access the list from the variable, like this:

b = x$a

but the above obviously won't work because the variable "a" is a string.

Is there any way to do this? I'm not too familiar with R data types, and I've tried browsing ?Extract, and ?"`" but haven't had much success.

I'm getting these variables in this format from a 3rd party and I have no control over them, but I need to work with them somehow.

Any help appreciated.

Upvotes: 0

Views: 197

Answers (1)

arvi1000
arvi1000

Reputation: 9592

x[['1']] works, but you're calling x[['`1`']]

x <- list(`1`=1, `2`=2, `3`=3)
a = '`1`'

# doesn't work, bc the first element is named "1" not "`1`"
x[[a]]

# works fine
other_a = '1'
x[[other_a]]

Here's an example that takes away the backticks/quote thing, which is what's confounding you

x <- list(apple=1, banana=2)
a = 'orange'

# this doesn't work, just as you'd expect -- returns null because there's no such element
x[[a]] 

other_a = 'apple'

# this works fine, and gets you the value of the element named apple
x[[other_a]] 

Upvotes: 1

Related Questions