One can select a single element from a list using either "[[" or "$", as you can see here:
They are similar, but there are a few things you should be aware of. By default, "$" allows partial matching, if the element can be uniquely identified:
a_list <- list(foo1 = 1) a_list$foo # 1 a_list <- list(foo1 = 1, foo2 = 3, b = 4) a_list$foo # NULL
Partial matching behaviour can also be used with "[[":
a_list <- list(foo1 = 1) a_list[["foo"]] # NULL a_list[["foo", exact = FALSE]] # 1
Partial matching can bite you, so if you want to be on the safe side, use "[[" to access elements from a list.
Did you know that you can index a NULL object?
x <- NULL x[["foo"]] typeof(x) # "NULL" x[["foo"]] <- 1 typeof(x) # "list"
This might be a problem, if for example you are in a function, with x an argument of this function, which you expect to be a list containing several elements. In this case, ensure your expectations are fulfilled, for example by using:
checkmate::assertList(x = x, any.missing = FALSE, min.len = 1, names = "named")
Make a promise. Show up. Do the work. Repeat.