2

I want to clearly understand difference between [] and [[]] and I ran below snippet of code. I know that [[]] returns a individual member of list while [] returns list of elements. But then why do i get an error when I run "all_data[1]=list(5,6)" but no error when I run "all_data[[1]]=list(5,6)" or when I run "all_data[2]=5"

all_data <- list()
all_data[2]=5
all_data[1]=list(5,6)



all_data[[1]]=list(5,6)
all_data

as per the fist comment of the first answer, adding a line of a code which helps to understand further

all_data[1:2] <- list(5,6)
user2543622
  • 5,760
  • 25
  • 91
  • 159
  • This blog post explains subsetting operations (including subsetting and assignment) very clearly http://adv-r.had.co.nz/Subsetting.html. @Senor O I just wanted to copy the link in a comment rather than copy paste from the blog and answer the question. There is a section there "subsetting and assignment" which addresses this specific question. – konvas Jun 02 '14 at 16:25
  • @konvas that doesn't answer his specific question – Señor O Jun 02 '14 at 16:27

1 Answers1

5

all_data[1]=list(5,6) gives you a Warning (not an error) that the lengths aren't the same. You can't set a one-element list to a two-element list. It's like trying x <- 1; x[1] <- 1:2.

But you can set one element of a list to contain another list, which is why all_data[[1]]=list(5,6) works.

Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • 2
    I think adding the example `all_data[1:2] <- list(5,6)` might help with the understanding as well. – Dason Jun 02 '14 at 16:36
  • I understand how this works, but it doesn't seem intuitive. Why must `a` in `List[1] <- a` match the structure of `List[1]`, while it can be anything to replace `List[[1]] <- a`? It would make sense for `List <- list(); List[1] <- list(5,6)` to be the same as `List <- list(list(5, 6))` – Señor O Jun 02 '14 at 16:43
  • @SeñorO And what should something like `x <- numeric(); x[1] <- c(5,6)` give? How about `x <- 1:5; x[2] <- c(5,6)`. – Dason Jun 02 '14 at 18:17
  • @Dason nothing, because `x[1]` would never return a length 2 vector, whereas `List[1]` can return a length 2 list. – Señor O Jun 02 '14 at 18:26
  • @SeñorO - No. List[1] returns a 1 element list. That element itself could be a list that has multiple elements but List[1] will always give a sublist of length 1. – Dason Jun 02 '14 at 18:48
  • @Dason I see it now - that makes sense – Señor O Jun 02 '14 at 19:06