R - creating a function f(x) from integral of g(x,y)dy

Viewed 93

I'm working in R and I would like to know if it is possible to create a function f(x) obtained from an integral of a function g(x,y) with respect to the variable y for example in (0,1), lets say:

I tried this code

f <- function(x){integrate(function(y){g(x,y),0, 1)}

(with g(x,y) an explicit function) but it didn't work unless I fixed x.

Also some help with formatting would be awesome since this is unreadable! Thanks!

3 Answers

It is avaiable. You can try

f <- function(x,y) x + y
f(1,2)

it <- function(x) {
    g <- function(y) f(x,y)
    integrate(g, 0,1)
}
it(1)

{caracas} might be what you're looking for. Here is a reproducible example:

library(reticulate)
library(caracas)

# make symbols x and y:
x <- symbol("x")
y <- symbol("y")

Function g:

g <- x ** 3 - y ** 3
g
#> [caracas]:  3    3
#>            x  - y

Function f (integral of g w.r.t 'y' from 0 to 1):

f <- int(g, var = "y", lower = 0, upper = 1)
f
#> [caracas]:  3   1
#>            x  - -
#>                 4

Function h (integral of f w.r.t 'x' from 0 to 1):

h <- int(f, var = "x", lower = 0, upper = 1)
h
#> [caracas]: 0

Maybe you can try this

g <- function(x, y) x^4 + y^2
f <- Vectorize(function(x) {
    integrate(function(y) g(x, y), 0, 1)$value
})

and you will see

> f(c(1, 2, 3, 4))
[1]   1.333333  16.333333  81.333333 256.333333

and curve(f, 0, 5) gives

enter image description here

Related