What is difference between single bracket and double bracket in R

r

#1

I was studying about subsetting in R . I have created a list and I have used both bracket in it but I am getting different result
x<-list(foo=1:4,bar=1)
x[1]
$foo
[1] 1 2 3 4

x[[1]]
[1] 1 2 3 4


#2

Hi Sid,

[[ is similar to [, except it can only return a single value and it allows you to pull pieces out of a list

You can use double brackets to select elements in more or less the same way as single brackets. The difference between single and double is that with double brackets any element names are not displayed:

You need [[ when working with lists. This is because when [ is applied to a list it always returns a list: it never gives you the contents of the list. To get the contents, you need [[:

Hope it helps :smile:

Regards,
Raghavendra