Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R lists -- how are element names handled?

Tags:

syntax

list

r

I have noticed this unexpected feature:

foo <- list(whatever=1:10)

Now, the following works as well:

foo$wha
foo$w
foo$whateve

However, the following does not:

foo[["wha"]]

This has the unexpected consequences (unexpected for me, that is) that if you have two potential names, like "CXCL1" and "CXCL11", and you want to know whether CXCL1 is not null by inspecting !is.null(foo$CXCL1), it will return TRUE even if CXCL1 null, but CXCL11 isn't.

My questions are:

  1. How does that work?
  2. What is the difference between foo$whatever and foo[["whatever"]]?
  3. Why would anyone want this behavior and how do I disable it?
like image 769
January Avatar asked Sep 24 '15 13:09

January


People also ask

Can you name list elements in R?

The list can be created using list() function in R. Named list is also created with the same function by specifying the names of the elements to access them. Named list can also be created using names() function to specify the names of elements after defining the list.

How does list work in R?

R list is the object which contains elements of different types – like strings, numbers, vectors and another list inside it. R list can also contain a matrix or a function as its elements. The list is created using the list() function in R. In other words, a list is a generic vector containing other objects.

How do I see the elements in a named list in R?

Accessing List Elements. Elements of the list can be accessed by the index of the element in the list. In case of named lists it can also be accessed using the names.

How do I select an element from a list in R?

We can use the [[index]] function to select an element in a list. The value inside the double square bracket represents the position of the item in a list we want to extract.


1 Answers

  1. Partial matching only works with unique initial subsequences of list names. So, for example:

    > l <- list(score=1, scotch=2)
    > l$core #only INITIAL subsequences
    NULL
    > l$sco #only UNIQUE subsequences
    NULL
    > l$scor
    [1] 1
    
  2. Both [[ and $ select a single element of the list. The main differences are that $ does not allow computed indices, whereas [[ does, and that partial matching is allowed by default with operator $ but not with [[.

  3. These Extract or Replacement operators come from S, although R restricts the use of partial matching, while S uses partial matching in most operators by default.

In your example, if CXCL1 and CXCL11 coexist and you index foo$CXCL1, that's not a partial match and should return CXCL1's value. If not, maybe there's another problem.

I should point out, [[ not allowing partial matching as default starts from version R 2.7.0 onwards.

like image 103
mescarra Avatar answered Oct 18 '22 05:10

mescarra