Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about lists in R? [duplicate]

Tags:

r

I come from a Python background but have to learn R for a job, and I am confused about lists.

I understand named lists can be (roughly) equivalent to Python dictionaries, and I can look up elements either by index using example_list[[1]] or example_list$name if I know the name of the key.

example_list <- list(a=1, b=3, c="d", f=list(1:4))

example_list$c #"d"
example_list$f #[[1]] [1] 1 2 3 4
example_list$f[[1]] # [1] 1 2 3 4
example_list[["f"]][[1]][[1]] # [1] 1

When I was playing around, I noticed to get "1" from f, I had to use [[1]] twice? I was expecting f to be [1, 2, 3, 4] but it seems to be [[1,2,3,4]], am I understanding this correctly?

like image 743
nos codemos Avatar asked Dec 22 '25 06:12

nos codemos


1 Answers

Keep in mind the distinction in R between lists and vectors. In R, 1:4 is a vector. list(1:4) is a list of length 1 that contains a vector of length 4. as.list(1:4) is a list of length 4 where each element contains a vector of length 1.

Consider these alternatives

example_list <- list(a=1, b=3, c="d", f=1:4)
example_list[["f"]][1]
# [1] 1
example_list$f[1]
# [1] 1

or

example_list <- list(a=1, b=3, c="d", f=as.list(1:4))
example_list$f[[1]]
# [1] 1
example_list[["f"]][[1]]
# [1] 1

or

example_list <- list(a=1, b=3, c="d", f=list(1,2,3,4))
example_list$f[[1]]
# [1] 1
example_list[["f"]][[1]]
# [1] 1

In your case you added an extra level of nesting with the list() call which you wouldn't normally use if just storing a vector. list(1:4) is different than list(1,2,3,4)

If it makes it easier to understand, you can also look at the JSON representation to see the extra layer of nesting

example_list <- list(a=1, b=3, c="d", f=list(1:4))
jsonlite::toJSON(example_list, auto_unbox = TRUE)
# {"a":1,"b":3,"c":"d","f":[[1,2,3,4]]} 
like image 187
MrFlick Avatar answered Dec 23 '25 23:12

MrFlick