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:
foo$whatever
and foo[["whatever"]]
?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.
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.
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.
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.
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
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 [[
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With