Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access parts of a list in R

Tags:

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

like image 565
user124123 Avatar asked Dec 21 '22 08:12

user124123


1 Answers

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
like image 173
Ricardo Saporta Avatar answered Jan 27 '23 10:01

Ricardo Saporta