In R, What is the difference between df["x"] and df$x

Viewed 7411

Where can I find information on the differences between calling on a column within a data.frame via:

df <- data.frame(x=1:20,y=letters[1:20],z=20:1)

df$x
df["x"]

They both return the "same" results, but not necessarily in the same format. Another thing that I've noticed is that df$x returns a list. Whereas df["x"] returns a data.frame.

EDIT: However, knowing which one to use in which situation has become a challenge. Is there a best practice here or does it really come down to knowing what the command or function requires? So far I've just been cycling through them if my function doesn't work at first (trial and error).

7 Answers

One thing I haven't seen explained explicitly is that [ and [[ can be used to select based on the value of a variable or expression while $ cannot. I.E you can do:

> example_frame <- data.frame(Var1 = c(1,2), Var2 = c('a', 'b'))
> x <- 'Var1'

> example_frame$x
NULL  # Not what you wanted

> example_frame[x]
  Var1
1    1
2    2

> example_frame[[x]]
[1] 1 2

> example_frame[[ paste(c("V","a","r",2), collapse='') ]]
[1] a b
Levels: a b

The differences between [ and [[ have been well covered by other posts and other questions.

Related