Wednesday, August 1, 2018

R difference between [[]] and []




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)

Answer



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.



No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...