So I'm kind of new to R, and I need to plot some functions. My understanding of curve in R is that it requires a function that has x as its single input. Since my functions are all just different representations of the same main function, I first thought I would create the main function, and then I would define each specific function individually.
# The principal function
puiss <- function(theta, inf, sup) {
for(k in inf:sup) {
total += (choose(30,k) * (theta^k) * ((1-theta)^(30-k)))
}
}
# The specific functions I need to draw on the same plot
p1 <- function(x) { puiss(x,2,13) }
p2 <- function(x) { puiss(x,3,14) }
p3 <- function(x) { puiss(x,3,13) }
# Can't even get to trace just a single one... :'(
curve(p1,
0, 1, # from 0 to 1
main="puissance(theta)", # title
xlab="x", ylab="theta") # axes
curve(p2, add=T) # adding the other function
curve(p3, add=T) # adding the other function
I get this error:
'expr' did not evaluate to an object of length 'n'
I've tried multiple approaches, but this one seemed to be the closest one to what it should have been.
Among other alternatives, I've tried:
- changing from
<-to=for the specific functions - using no
{}(brackets) for the specific functions - plugging the
forloop directly into the curve and replacingthetabyxandinf:supappropriately - trying to use
p1(x)insidecurve - I've also read that some times
Vectorize()is needed, so I've triedVectorize(p1)insidecurve
What am I doing wrong?
It might help to disclose that my main function is just a Binomial(30, theta)'s mass function (probability) evaluated in different regions (the summation within the boundaries, my sigma which is a for loop because I couldn't figure out how to properly create a sigma function in R). In other words, it is a cumulative distribution function.
Ultimately, I'm trying to plot the 3 specific functions together on the same plot.
Thanks for the help! :)