The technique of indexing a data frame with an empty index features several times in Hadley Wickam's Advanced R, but is only explained there in passing. I'm trying to figure out the rules governing indexing a list with an empty index. Consider the following four statements.
> (l <- list(a = 1, b = 2))
$a
[1] 1
$b
[1] 2
> (l[] <- list(c = 3))
$c
[1] 3
> l
$a
[1] 3
$b
[1] 3
> l[]
$a
[1] 3
$b
[1] 3
Questions:
Empty list has no index.
You can create an empty list using an empty pair of square brackets [] or the type constructor list() , a built-in function that creates an empty list when no arguments are passed. Square brackets [] are commonly used in Python to create empty lists because it is faster and more concise.
python lists are 0-indexed. So the first element is 0, second is 1, so on. So if the there are n elements in a list, the last element is n-1. Remember this!
The elements of a list can be accessed by an index. To do that, you name the list, and then inside of a pair of square brackets you use an index number, like what I'm showing right here. 00:17 That allows access to individual elements within the list. The indexing for the list is zero-based.
In short l[]
will return the whole list.
(l <- list(a = 1, b = 2))
l[]
l[] <- list(c=3)
is essentially reassigning what was assigned to each index to now be the result of list(c=3)
. For this example, it is the same as saying l[[1]] <- 3
and l[[2]] <- 3
. From the ?'['
page, which mentions empty indexing a few times:
When an index expression appears on the left side of an assignment (known as subassignment) then that part of x is set to the value of the right hand side of the assignment.
and also
An empty index selects all values: this is most often used to replace all the entries but keep the attributes.
So, I roughly take this to mean each index of l
should evaluate to list(c=3)
.
When you enter (l[] <- list(c = 3))
what is being returned is the replacement value. When you then enter l
or l[]
you will see that the values at each index have been replaced by list(c=3)
.
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