user330
user330

Reputation: 1290

Is there a method to evaluate functions with different input values?

I have the following data:

  A1= c(a=10,b=5,c=4)
  A2= c(a=5,b=6,c=4)
  A3= c(a=1,b=2,c=3)

The function is:

 y=a+exp(b+1)-c

I want to get the following table when I substitute the values of A1, A2, A3 in the function.

yA1 409.42
yA2 1097.63
yA3 18.08

Please advise if you require further information.

Upvotes: 0

Views: 60

Answers (1)

jdobres
jdobres

Reputation: 11957

This is easier to accomplish if you store your variables as lists, and then use sapply:

vars <- list(
  A1= list(a=10,b=5,c=4),
  A2= list(a=5,b=6,c=4),
  A3= list(a=1,b=2,c=3)
)

y <- sapply(vars, function(x) with(x, a+exp(b+1)-c))

        A1         A2         A3 
 409.42879 1097.63316   18.08554 

And your desired format:

data.frame(yA = names(y), value = y, row.names = NULL)

  yA      value
1 A1  409.42879
2 A2 1097.63316
3 A3   18.08554

You can also do a more succinct version with expr and eval:

my_formula <- expr( a+exp(b+1)-c )
y <- sapply(vars, eval, expr = my_formula)

        A1         A2         A3 
 409.42879 1097.63316   18.08554 

Upvotes: 1

Related Questions