[R] function that uses a variable name as the parameter
Wacek Kusnierczyk
Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Wed Nov 12 14:28:07 CET 2008
David Croll wrote:
> Hello dear R people!
>
>
> Several times it occurred to me that a function that uses a variable name as a parameter would be helpful, but I did not find out how to write such a function. I have experience in several programming language, but I did not come across a helpful trick...
>
> What I want to have is...
>
> a <- 12 # starting value
>
> add <- function(variable,increment) {
>
> variable <- variable + increment
>
> }
>
> # by typing a and 25 for example, you specify that 25 will be added to the variable a...
>
> add(a,25)
>
> # the new a equals 12 + 25 = 37
>
>
add = function(variable, value)
assign(deparse(substitute(variable)), variable + value,
envir=parent.frame())
a = 1
add(a, 2)
a
# 3
addtoa = function(value)
add(a, value)
addtoa(10)
a
# still 3
add = function(variable, value)
assign(deparse(substitute(variable)), variable + value, inherits=TRUE)
addtoa(10)
a
# 13
?assign
vQ
More information about the R-help
mailing list