Problems of building a custom function in R
I would like to program and build this function in R
:
The code I use is:
js <- sapply( seq(1,50, 1), FUN <- function(x) x^{-4})
pim <- sapply(seq(1,50, 1), FUN <- function(x) 2*pi*x)
beta <- function(x) sum(js*sqrt(2)*cos(pim*x))
but so far this returns the correct values for each point, I ran into a problem when I try to plot it using a curve function as I get:
Error in curve(beta, 0, 1) :
'expr' did not evaluate to an object of length 'n'
In addition: Warning messages:
1: In pim * x :
longer object length is not a multiple of shorter object length
2: In js * sqrt(2) * cos(pim * x) :
longer object length is not a multiple of shorter object length
Could you please help me fix this issue and get a working plot? Thank.
source to share
There is an error in your function beta
. When you use sum
it like this, it takes the sum of the entire vector for t = 1, ..., T. You don't want to do that. Instead, you want to evaluate this function for every t. So, with a little change to, beta
you can use the function curve
.
js <- sapply( seq(1,50, 1), function(x) x^{-4})
pim <- sapply(seq(1,50, 1), function(x) 2*pi*x)
beta <- function(x) {
sapply(x, function(y) sum(js*sqrt(2)*cos(pim*y)))
}
curve(beta, 0 ,1)
source to share
I am very surprised what you both use sapply
inside these functions. The formula can be literally copied into R:
beta <- function(x, n=50){
j <- seq_len(n)
sum(
j^(-4)* sqrt(2) * cos(2*j*pi*x)
)
}
You can use any expression that contains x
in the function curve
:
curve(sapply(x,beta),0,1)
gives the same plot.
On the side: if you wanted to beta
be vectorized, you could actually add sapply
inside, or you could do:
beta_vect <- Vectorize(beta)
curve(beta_vect,0,1)
works also.
source to share