user124123
user124123

Reputation: 1683

How to access parts of a list in R

I've got the optim function in r returning a list of stuff like this:

[[354]]
    r     k sigma 
389.4 354.0 354.0 

but when I try accessing say list$sigma it doesn't exist returning NULL.

I've tried attach and I've tried names, and I've tried assigning it to a matrix, but none of these things would work Anyone got any idea how I can access the lowest or highest value for sigma r or k in my list??

Many thanks!!

str gives me this output:

List of 354
 $ : Named num [1:3] -55.25 2.99 119.37
  ..- attr(*, "names")= chr [1:3] "r" "k" "sigma"
 $ : Named num [1:3] -53.91 4.21 119.71
  ..- attr(*, "names")= chr [1:3] "r" "k" "sigma"
 $ : Named num [1:3] -41.7 14.6 119.2

So I've got a double within a list within a list (?) I'm still mystified as to how I can cycle through the list and pick one out meeting my conditions without writing a function from scratch

Upvotes: 5

Views: 11605

Answers (3)

Ricardo Saporta
Ricardo Saporta

Reputation: 55340

The key issue is that you have a list of lists (or a list of data.frames, which in fact is also a list).
To confirm this, take a look at is(list[[354]]).

The solution is simply to add an additional level of indexing. Below you have multiple alternatives of how to accomplish this.


you can use a vector as an index to [[, so for example if you want to access the third element from the 354th element, you can use

 myList[[ c(354, 3) ]]

You can also use character indecies, however, all nested levels must have named indecies.

names(myList) <- as.character(1:length(myList))
myList[[ c("5", "sigma") ]]

Lastly, please try to avoid using names like list, data, df etc. This will lead to crashing code and erors which will seem unexplainable and mysterious until one realizes that they've tried to subset a function


Edit:

In response to your question in the comments above: If you want to see the structure of an object (ie the "makeup" of the object), use str

> str(myList)
List of 5
 $ :'data.frame': 1 obs. of  3 variables:
  ..$ a    : num 0.654
  ..$ b    : num -0.0823
  ..$ sigma: num -31
 $ :'data.frame': 1 obs. of  3 variables:
  ..$ a    : num -0.656
  ..$ b    : num -0.167
  ..$ sigma: num -49
 $ :'data.frame': 1 obs. of  3 variables:
  ..$ a    : num 0.154
  ..$ b    : num 0.522
  ..$ sigma: num -89
 $ :'data.frame': 1 obs. of  3 variables:
  ..$ a    : num 0.676
  ..$ b    : num 0.595
  ..$ sigma: num 145
 $ :'data.frame': 1 obs. of  3 variables:
  ..$ a    : num -0.75
  ..$ b    : num 0.772
  ..$ sigma: num 6

Upvotes: 10

agstudy
agstudy

Reputation: 121568

Using , do.call you can do this :

 do.call('[',mylist,354)['sigma']

Upvotes: 0

Theodore Lytras
Theodore Lytras

Reputation: 3965

If you want -for example- all the sigmas, you can use sapply:

sapply(list, function(x)x["sigma"])

You can use that to find the minimum and maximum:

range(sapply(list, function(x)x["sigma"]))

Upvotes: 1

Related Questions