Best practices for referencing columns in a data.frame when writing R packages

Viewed 51

Why might one prefer using one of the following approaches to reference columns in a data.frame when writing functions inside an R package?

d <- data.frame(x = c(1, 2))

# This is one way to extract a column from a data.frame. 
# Using dollar sign notation
d$x
#> [1] 1 2

# This is another way to extract a column from a data.frame
d[["x"]]
#> [1] 1 2

Created on 2021-04-19 by the reprex package (v1.0.0)

I vaguely remember reading that the second approach is preferable when programming with R, but I don't remember why. The dollar sign approach is more concise, so ceteris paribus, I would rather use the dollar sign approach.

1 Answers

The dollar can work only if we provide the exact column name. Suppose, if the column name is stored in an object or say

d$name(d)[1]

or

nm1 <- 'x'
d$nm1

Instead it would be

d[[nm1]]

it wouldn't work because it is looking for a literal match

Also, when using the $, there is a partial match. Suppose, we have column names, 'x', 'xx', 'xxy', the 'x' could match either one of them

Related