Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between [[]] and $ in list indexing?

Tags:

r

Can anyone explain why list1 and list2 below are not identical?

list1 <- list()
lev1 <- "level1"
lev2 <- "level2"
list1[[lev1]][[lev2]] <- 1
list1
$level1
level2 
     1 

list2 <- list()
list2$level1$level2 <- 1
list2
$level1
$level1$level2
[1] 1
like image 552
Kevin Burnham Avatar asked Sep 19 '16 17:09

Kevin Burnham


People also ask

What does [- 1 :] mean in Python?

Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.

What is the difference between positive and negative indexing?

- Python arrays & list items can be accessed with positive or negative numbers (also known as index). - For instance our array/list is of size n, then for positive index 0 is the first index, 1 second, last index will be n-1.

What is the use of * in list?

The star(*) operator unpacks the sequence/collection into positional arguments. So if you have a list and want to pass the items of that list as arguments for each position as they are there in the list, instead of indexing each element individually, you could just use the * operator.

What is difference between slicing and indexing in Python?

What are Indexing and Slicing? Indexing: Indexing is used to obtain individual elements. Slicing: Slicing is used to obtain a sequence of elements. Indexing and Slicing can be be done in Python Sequences types like list, string, tuple, range objects.


1 Answers

This is occurring because you are assigning a length 1 vector to a NULL atomic vector.

From help(Extract) -

When $<- is applied to a NULL x, it first coerces x to list(). This is what also happens with [[<- if the replacement value value is of length greater than one: if value has length 1 or 0, x is first coerced to a zero-length vector of the type of value.

Change the assignment to ... <- 1:2 (or something other than a length 0 or 1 vector) and you will get the same result in both code blocks.

list1 <- list()
lev1 <- "level1"
lev2 <- "level2"
list1[[lev1]][[lev2]] <- 1:2
list1
# $level1
# $level1$level2
# [1] 1 2

list2 <- list()
list2$level1$level2 <- 1:2
list2
# $level1
# $level1$level2
# [1] 1 2

A simpler example of this, as mentioned by @alexis_laz in the comments, is just to begin with a NULL atomic vector and look at what happens.

x <- NULL
## assign a length 1 vector --> atomic result
x[["lev1"]] <- 1
x
# lev1 
#    1 

y <- NULL
## assign a length > 1 vector --> list result
y[["lev1"]] <- 1:2
y
# $lev1
# [1] 1 2

The result from $<- is always a list so I have omitted it here.

like image 51
Rich Scriven Avatar answered Sep 26 '22 19:09

Rich Scriven