[R] Symbolic references - passing variable names into functions
Gabor Grothendieck
ggrothendieck at gmail.com
Wed Aug 12 17:09:33 CEST 2009
Returning the changed value as in Erik's answer is probably the
most common and R-like solution but here are two others. The
assign/get approach is perhaps the closest to what you are asking
for.
# replacement function approach
# replacement function - rhs is formula whose response is assigned to
"dataf<-" <- function(data, value) {
v <- all.vars(value)
data[[v[1]]] <- data[[v[2]]]
data
}
BOD <- datasets::BOD
BOD
dataf(BOD) <- Time ~ demand
BOD
# assign/get approach
dataf <- function(data, col1, col2, env = parent.frame()) {
data.name <- deparse(substitute(data))
data <- get(data.name, env)
data[col1] <- data[col2]
assign(data.name, data, env)
}
BOD <- datasets::BOD
BOD
dataf(BOD, "Time", "demand")
BOD
On Wed, Aug 12, 2009 at 10:27 AM, Alexander Shenkin<ashenkin at ufl.edu> wrote:
> Hello All,
>
> I am trying to write a function which would operate on columns of a
> dataframe specified in parameters passed to that function.
>
> f = function(dataf, col1 = "column1", col2 = "column2") {
> dataf$col1 = dataf$col2 # just as an example
> }
>
> The above, of course, does not work as intended. In some languages one
> can force evaluation of a variable, and then use that evaluation as the
> variable name. Thus,
>
> > a = "myvar"
> > (operator)a = 1
> > myvar
> [1] 1
>
> Is there some operator which allows this symbolic referencing in R?
>
> Thanks,
> Allie
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list