22

I am trying to make a list and access its cells later in R. These [], [[]] are really bugging me. I tried reading the help online but I don't understand why c["var1"][1] and c$"var"[1] are different.

What are the actual uses for these three notations [], [[]], $?

v <- vector("character", 5)
v[1] <- 'a'
v[2] <- 'a'
v[4] <- 'a'
v
# [1] "a" "a" ""  "a" "" 
c <- list(v, v)
names(c) <- c("var1", "var2")
c
# $var1
# [1] "a" "a" ""  "a" "" 

# $var2
# [1] "a" "a" ""  "a" "" 

c["var1"][1]
# $var1
# [1] "a" "a" ""  "a" "" 

c$"var1"[1]
# [1] "a"
5
  • 3
    You need c[['var1']][1] as the [ is still a list Commented Sep 28, 2015 at 9:25
  • 1
    Use str to see the structure of an object. See for instance str(c[1]) opposed to str(c[[1]]). No need of quotes when using $: c$var1 works just fine. Commented Sep 28, 2015 at 9:26
  • 2
    Can you confirm that you have read help("[") and section 6.1 of An Introduction to R? Commented Sep 28, 2015 at 9:27
  • @Roland No..Ok i am looking into it Commented Sep 28, 2015 at 9:28
  • @Roland help("[") is really helpful... Commented Sep 28, 2015 at 9:56

1 Answer 1

52

All these techniques give different outputs.

List[ ] returns a list - a sub-list of the original list List.

List[[ ]] returns the single object stored at that position in List.

If it is a named list, then

List$name and List[["name"]] return the same thing;

List["name"] returns a list. Consider the following example:

> List <- list(A = 1,B = 2,C = 3,D = 4)
> List[1]
$A
[1] 1

> class(List[1])
[1] "list"
> List[[1]]
[1] 1
> class(List[[1]])
[1] "numeric"
> List$A
[1] 1
> class(List$A)
[1] "numeric"
> List["A"]
$A
[1] 1

> class(List["A"])
[1] "list"
> List[["A"]]
[1] 1
> class(List[["A"]])
[1] "numeric"
Sign up to request clarification or add additional context in comments.

1 Comment

There are special cases where List$name and List[["name"]] don't return the same thing - see stackoverflow.com/questions/14153904/….

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.