1

This would seem to be a straightforward problem but I can't find an answer for it...

How do I write a function where one of the calls refers to a specific variable name?

For example, if I have a data frame:

data=structure(list(x = 1:10, treatment = c(1L, 2L, 1L, 2L, 1L, 2L, 
1L, 2L, 1L, 2L)), .Names = c("x", "treatment"), row.names = c(NA, 
-10L), class = "data.frame")

I can write a trivial function that adds treatment to the other variable in the data frame but this only works if there is a variable called "treatment" in d.

ff=function(data,treatment){data+treatment)}
ff(data,data$treatment)

This works but I want to set it up so the user doesn't call data$Var in the function.

4
  • ff = function(data, var1, var2) {data[, var1] + data[, var2]} ? Is that what you're looking for? Commented May 26, 2015 at 20:08
  • When I run that I get an error that the variables are not found Commented May 26, 2015 at 20:13
  • To use @JoshW.'s solution, var1 and var2 would need to be passed to the function as character strings, otherwise you'd need deparse(substitute(var1)). Commented May 26, 2015 at 20:14
  • That's because quote() returns a symbol and you need a string. Try it with deparse(substitute()). Commented May 26, 2015 at 20:17

1 Answer 1

1

Is this what you want?

ff <- function(data, colname) {
   data + data[[colname]]
}
ff( data, "treatment" )

or

ff <- function(data, column) {
  colname <- deparse(substitute(column))
  data + data[[colname]]
}
ff( data, treatment )

(the later can lead to hard to find bugs if someone tries something like ff(data, 1:10))

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.