简体   繁体   中英

Passing arguments for variables in a function

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. Eg, 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 (eg, `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 (eg, 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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM