cloud
cloud

Reputation: 23

R- Get a list of output value from a formula

I have a formula looks something like this: y=2+3x+x^2 and I have a list of inputs values that I would like to plug in x then graph it later.

So what I do is

x<-seq(-2,2, length.out=20)
formula <- y~2+3*x+x^2

But I'm not sure how to plug in a list of x values to the formula and get the output value from the codes. Any help would be appreciated.

Upvotes: 1

Views: 1146

Answers (3)

G. Grothendieck
G. Grothendieck

Reputation: 270020

fn$ in gsubfn can be used to convert a formula to a function. If a function such as identity is prefaced with fn$ then a formula in the arguments will be converted to a function and then the function that fn$ prefaces will be run. The LHS of the formula should be the input variable to the function or empty. In the latter case it will use the free variables on the RHS as the arguments. The RHS is the body.

library(gsubfn)

fo[[2]] <- NULL   # remove LHS
fun <- fn$identity(fo)   # create function from formula

fun
## function (x) 
## 2 + 3 * x + x^2

fun(x)
##  [1]  0.00000000 -0.16620499 -0.24376731 -0.23268698 -0.13296399  0.05540166
##  [7]  0.33240997  0.69806094  1.15235457  1.69529086  2.32686981  3.04709141
## [13]  3.85595568  4.75346260  5.73961219  6.81440443  7.97783934  9.22991690
## [19] 10.57063712 12.00000000

Upvotes: 0

NM_
NM_

Reputation: 2009

You can make your formula into a function and use sapply:

x = seq(-2,2, length.out=20)

my.function = function(x){
  return(2+3*x+x^2)
}

y = sapply(x, my.function)
> y
 [1]  0.00000000 -0.16620499 -0.24376731 -0.23268698 -0.13296399  0.05540166  0.33240997
 [8]  0.69806094  1.15235457  1.69529086  2.32686981  3.04709141  3.85595568  4.75346260
[15]  5.73961219  6.81440443  7.97783934  9.22991690 10.57063712 12.00000000

If you would like a list, then use lapply instead of sapply.

Upvotes: 0

Sonny
Sonny

Reputation: 3183

You could have defined a function to calculate the formula as below:

getScore <- function(x) {
  2+3*x+x^2
}
x <- seq(-2,2, length.out=20)
getScore(x)
 [1]  0.00000000 -0.16620499 -0.24376731 -0.23268698 -0.13296399  0.05540166
 [7]  0.33240997  0.69806094  1.15235457  1.69529086  2.32686981  3.04709141
[13]  3.85595568  4.75346260  5.73961219  6.81440443  7.97783934  9.22991690
[19] 10.57063712 12.00000000

Upvotes: 1

Related Questions