Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is R's list() function actually creating a nested list?

Tags:

list

r

R may have its own loigc but list() did not give me what I expected.

l1 <- list(1,2)
$> l1
[[1]]
[1] 1

[[2]]
[1] 2

To retrieve the element, I need to use double-bracket, i.e.,

$> l1[[1]]
[1] 1
$> class(l1[[1]])
"numeric"

Single-bracket gives me, a sub-list (which is also a list object):

$> l1[1]
l1[[1]]
[1] 1
$> class(l1[1])
"list"

I am not saying this is wrong; this isn't what I expected because I was trying to create a 1-dimensional list whereas what I actually get is a nested list, a 2-dimensional object.

What is the logic behind this behaviour and how do we create an OO type list? i.e., a 1-dimensional data structure?

The behaviour I am expecting, with a 1 dimensional data structure, is:

$> l1[1]
[1] 1
$> l1[2]
[2] 2
like image 682
stucash Avatar asked Oct 20 '25 04:10

stucash


1 Answers

If you want to create a list with the two numbers in one element, you are looking for this:

l1 <- list(c(1, 2))
l1
#> [[1]]
#> [1] 1 2

Your code basically puts two vectors of length 1 into a list. To make R understand that you have one vector, you need to combine (i.e., c()) the values into a vector first.

This probably becomes clearer when we create the two vectors as objects first:

v1 <- 1
v2 <- 2
l2 <- list(v1, v2)
l2
#> [[1]]
#> [1] 1
#> 
#> [[2]]
#> [1] 2

If you simply want to store the two values in an object, you want a vector:

l1 <- c(1, 2)
l1
#> [1] 1 2

For more on the different data structures in R I recommend this chapter: http://adv-r.had.co.nz/Data-structures.html

For the question about [ and [[ indexing, have a look at this classic answer: https://stackoverflow.com/a/1169495/5028841

like image 200
JBGruber Avatar answered Oct 21 '25 17:10

JBGruber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!