Ted Mosby
Ted Mosby

Reputation: 1456

Subset list by name of element in list

If I have a list like so:

x = rnorm(10)
y = rnorm(10)
df = cbind(x,y)
mylist=list(trace=df)

How can I pull out the trace data.frame by name? I've tried

trace_df = data.frame(mylist[mylist=='trace'])

but this searches through the list for data values equal to trace not for elements named list.

My thought behind this is that I have a large list of 7 or 8 elements and the position might change of them. So trace might be in index spot 1 or 2 or 5. So to make my code more reproducible I'd like to just search for the term trace and not search by index.

Upvotes: 4

Views: 10709

Answers (2)

Nad Pat
Nad Pat

Reputation: 3173

if its single element then use

mylist["trace"]

if you want to select multiple elements from list then,

name = c("trace")

mylist[name]

Upvotes: 3

lukeA
lukeA

Reputation: 54237

Pull it out with either mylist$trace or mylist[['trace']].

Upvotes: 4

Related Questions