Skip to content

Arguments of a function

6 messages · Henrique Dallazuanna, Lisa, Jim Lemon +2 more

#
Dear all,

I have a question about how to set arguments in my own function. For
example, I have a function that looks like this:

my.f <- function(a = x1, b = x2)
{
   x1 = equation 1
   x2 = equation 2
   x3 = equation 3
   y = a + b   
}

x1, x2, and x3 are temporary variables (intermediate results) calculated
from other variables within the funciton. I want to use two of these three
variables to calculate y, and write R script as below:

my.f(a = x1, b = x2)
 
or 

my.f(a = x2, b = x3)

The error information shows that: ?objects 'x1', 'x2', or 'x3' not found?. 

Can anybody help me solve this problem? Thanks in advance.

Lisa
#
Try this:

my.f <- function(a, b) {
	x1 <- 2 * 3
      x2 <- 3 / 6
      x3 <- 4 * 4 / 5 - sqrt(2)
	y <- get(deparse(substitute(a))) + get(deparse(substitute(b)))
	return(y)
}

my.f(x1, x2)
On Fri, Jan 8, 2010 at 4:15 PM, Lisa <lisajca at gmail.com> wrote:

  
    
#
That's what I want. Thank you so much. 
Lisa
Henrique Dallazuanna wrote:

  
    
#
On 01/09/2010 05:15 AM, Lisa wrote:
Hi Lisa,
Although you indicated that Henrique's solution worked, it looks to me 
as though you are confusing arguments with local variables. As you say, 
you are assigning the value of the sum of x1 and x2 to y. Since x1 and 
x2 only exist within the function, it would seem that you want:

my.f<-function(...) {
  x1<-(equation 1)
  x2<-(equation 2)
  x3<-(equation 3)
  y<-x1+x2
  return(y)
}

I suspect that you want to pass some values that will be used in the 
calculation of x1, x2 and x3 as arguments to the function (a and b?) 
thus the ellipsis in the function definition. Maybe what you are looking 
for is:

my.f<-function(a,b) {
  x1<-2 * a + 3
  x2<-b / 2
  x3<-(a + b) ^ 2
  y<-x1+x2
  return(y)
}

I hope this guess will be helpful to you.

Jim
#
You could define a list and then just access the
appropriate elements of that list:

my.f <- function(a, b)
{
   x1 = equation 1
   x2 = equation 2
   x3 = equation 3
   L <- list(x1, x2, x3)
   y <- L[[a]] + L[[b]]
}

my.f(1,2)
my.f(2,3)

  -Peter Ehlers
Lisa wrote:

  
    
#
Normally one designs their function to input a formula in such a case
rather than design it to take the names directly.  Thus:

f <- function(formula = ~ x1 + x2) {
  xs <- c(x1 = 1, x2 = exp(1), x3 = 2*pi)
  v <- all.vars(formula)
  stopifnot(length(v) == 2, all(v %in% names(xs)))
  sum(xs[v])
}

# test
f()
f(~ x1 + x2) # same
f(~ x2+x3)
On Fri, Jan 8, 2010 at 1:15 PM, Lisa <lisajca at gmail.com> wrote: