User7598
User7598

Reputation: 1678

Call variable from custom function

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.

Upvotes: 1

Views: 114

Answers (1)

Greg Snow
Greg Snow

Reputation: 49660

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))

Upvotes: 1

Related Questions