The $
operator is not as flexible as the [
operator for subsetting. There you can pass a string as a column name to do what you're looking for. From ?Extract
:
Both [[
and $
select a single element of the list. The main difference is that $
does not allow computed indices, whereas [[
does. x$name
is equivalent to x[["name", exact = FALSE]]
.
So, for your example that would look something like:
f <- function(dat, col) {dat[[col]]}
f(mtcars, "cyl")
#> [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4
Created on 2022-07-22 by the reprex package (v2.0.1)