E2R0NS
E2R0NS

Reputation: 103

Plotting a function in R where the input is of length 3

I am trying to plot a function I have defined in terms of a parameter x and plot the function over three values of x. I get an error about the lengths being different.

The length of the function is 1 while x is 3.

l <- seq(0, 7)
p <- c(5, 2, 9, 4, 4, 1, 1, 0)
loglikGeo <- function(beta){sum(p*log(dgeom(l, beta)))}
beta <- seq(0.01, 0.40, 0.01)
plot(beta, loglikGeo)

What is going on?

Upvotes: 0

Views: 103

Answers (1)

Ameer
Ameer

Reputation: 526

loglikGeo is defined as a function in your code so you cannot give it as as argument to plot. You need a vector in your y-argument in plot(). To apply a function to each element of a vector and return a vector of function values you can use sapply(vector,function). Replace the last line in your code with:

loglikGeo_values <- sapply(beta,loglikGeo)
plot(beta, loklikGeo_values)

Upvotes: 1

Related Questions