I am writing an R function that takes a data frame and variable name as inputs, performs some operations on the vector in the data frame corresponding to the input variable name, then returns the resulting vector.
While I can write this function using []
to index, I am trying to learn how to index with $
instead (I understand this may be a bad idea).
My best guess is that I need to paste together what I want as a string and somehow use parse()
, eval()
, substitute()
or some other function, but I suspect there might be a better way. Any help is appreciated.
# Create an arbitrary data frame
df <- data.frame(x = c("a","b","c","c","c"),
y = 1:5,
z = c(1,9,NA,0,NA))
# Create a vector with character "y",
# capturing the name of the column
# I want to work with in my data
M <- "y"
# Write a function that takes a
# data frame and a variable name,
# adds 5 to each value of that
# variable in the data frame, then
# prints the resulting numeric vector.
# Below produces the desired output
# of the function:
print(df$y + 5)
#####################################
# Define function to add 5 to a specified
# variable in the data frame using [] indexing
fun1 <- function(dat, var) {
df[ ,var] + 5
}
# Works with both quoted values and
# objects assigned quoted values
fun1(dat = df, var = "y")
fun1(dat = df, var = M)
# However, doesn't work when I use
# $ instead of []. See function below
# and corresponding results.
fun2 <- function(dat, var) {
df$var + 5
}
# Doesn't produce intended result
fun2(dat = df, var = "y")
fun2(dat = df, var = M)