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
  • 4,900
  • 22
  • 75
  • 136
  • 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
  • 168,168
  • 29
  • 327
  • 408