Subset list by name of element in list

Viewed 7537

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.

2 Answers

if its single element then use

mylist["trace"]

if you want to select multiple elements from list then,

name = c("trace")

mylist[name]
Related