Reputation: 3
I am brand-new to R and trying to understand the basic syntax of functions.
In both of the functions f(x1)
and g(x,1)
below, I would like to generate y=2
. Only the former works.
I'm familiar with the str_interp()
and paste()
functions, but those seem to work only in the context of strings, not variables. E.g., prefixnum <- str_interp("${prefix}${num}")
doesn't solve the issue.
My motivation is that I'd like to call a function by specifying components of variable names. My background is in Stata, where placeholders are designated with a backtick and a tick (e.g., `prefix'`num'). I've consulted a few relevant resources, to no avail.
As an aside, I've read varying thoughts about whether variables should be prefixed with its dataframe (e.g., df$var
). What is the logic behind whether or not to follow this convention? Why does f(df$x1)
work, but writing f(x1)
and modifying the function to be y <- df$var*2
not work?
df <- data.frame(x1=1)
f <- function(var) {
y <- var*2
y
}
f(df$x1)
g <- function(prefix,num) {
y <- df$prefixnum*2 #where "prefixnum" is a placeholder of some sort
y
}
g(x,1)
Upvotes: 0
Views: 39
Reputation: 388797
Possibly you are trying to pass column name as an argument to the function. You can try to paste prefix
and num
together to get column name and use that to subset dataframe.
g <- function(data, prefix, num) {
y <- data[[paste0(prefix, num)]] *2
y
}
g(df,'x', 1)
#[1] 2
Upvotes: 1