payne
payne

Reputation: 5229

Plotting functions of functions

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:

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! :)

Upvotes: 0

Views: 45

Answers (1)

bobbel
bobbel

Reputation: 2031

It seems you are using some Python (or similar) code in your function definition. Here is the R version of it, which for me will plot the results when calling curve.

puiss <- function(theta, inf, sup) {
  total = 0
  for(k in inf:sup) {
    # "+=" does not work for R
    total <- total + (choose(30,k) * (theta^k) * ((1-theta)^(30-k)))
  }
  # you need to use parentheses around total
  return(total)
}

Upvotes: 1

Related Questions