-2

Let's say I have a script, where I have a calculation like this:

calculation = c(
                a*b + 
                c*d + 
                e*f
                )

And then in another script I want to call that calculation using the source command.

I get an error saying "Object 'a' not found". What am I doing wrong?

Edit: I don't want to make a function, because this specific calculation is used as input in a complex program in r (apollo) - the input specifies a utility function in a logit regression.

zephryl
  • 14,633
  • 3
  • 11
  • 30
Victor Nielsen
  • 443
  • 2
  • 14

1 Answers1

1

You can capture your expression using expression(), then when you're ready, evaluate using eval():

calculation <- expression(a*b + d*e + f*g)

a <- 1
b <- 2
d <- 3
e <- 4
f <- 5
g <- 6

eval(calculation)
# 44
zephryl
  • 14,633
  • 3
  • 11
  • 30
  • Is there no way to make it return a * b + d * e + f * g when you call "calculation"? – Victor Nielsen Jan 03 '23 at 15:40
  • 1
    I don’t understand what you’re trying to do. You said in your question “I don't want to make a function,” but you’re asking to “return” something when you “call” it, which certainly sounds like a function. Please edit your original question to include a [reproducible example](https://stackoverflow.com/q/5963269/17303805) to make it clearer what you want, including code showing how you want to use `calculation`, an example of what the result should look like, and any example data needed to run the code. – zephryl Jan 03 '23 at 18:13