In general, when there's a special operator like *
or +
or %%
or $
or [
(etc), the first step in using or accessing more information about that operator is to put it in quotes. You want the help page for $
? Then do ?"$"
. Now, if you want to use that function in a non-standard fashion (as you want to do, and this is just fine), then you can make use to of do.call
, and the first argument to that function is a function in quotes: do.call(what="$", ...)
The next arguments to do.call
involve a list of arguments to be passed to the what
. This is much broad than what you asked, but I hope it is useful to you in the future.
Second, you don't need to use $
. You can just specify a column name for your data.frame. Instead of data$col
, try data[,"col"]
. For a data.frame, those are the same. If data
was a list, you could do data[["col"]]
.
Here are examples that specifically address your question:
# Data set to work with for examples
df <- data.frame(ran=rnorm(10), num=1:10)
# Function giving example of what you wanted
get.col <- function(dat, col){
do.call("$", list(dat, col))
}
get.col(df, "ran")
# A function providing an alternative approach
get.col2 <- function(dat, col){
dat[,col]
}
get.col2(df, "ran")