Misunderstanding of functions in R

Question

I have a vector

p <- seq(0,1,length=11)

That I want to use as the independent variable in the summation

enter image description here

If I craft a function that codes the summation by hand

f <- function(a){
a^0*(1-a)^5+a^1*(1-a)^4+...
}

and pass it p, then I get the correct output and no errors are thrown

results <- f(p)

I can plot it, results is the right length, everything's kosher. It just looks really ugly so I wanted to use sum() instead and tried

i <- 0:5    
g <- function(a,i){
    sum(a^i*(1-a)^(5-i))
}

but when I attempt g(p,i) it throws the error

longer object length is not a multiple of shorter object length

I believe the reason I'm getting this error is answered over here quite nicely, especially the part about recycling. sum cycles through the i vector as well as p at the same time, then starts over with p[7] and i[1] when it runs into the end of i. My question, however, is what is the CORRECT way to simplify f into g?


Show source
| function   | R   | sum   2017-10-04 22:10 3 Answers

Answers to Misunderstanding of functions in R ( 3 )

  1. 2017-10-04 22:10

    Maybe try this:

    g <- function(a, i){
      sum(sapply(i, function(x)a ^ x * (1 - a) ^ (5 - x)))
    }
    
    
    p <- seq(0, 1, length = 11)
    i <- 0:5
    g(p, i)
    # [1] 5.3999
    
  2. 2017-10-04 22:10

    The function that you want to compute isn't naturally vectorized with respect to p. sapply is a natural choice for mapping non-vectorized functions over a vector:

    f <- function(x){
      i <- 0:5
      sum(x^i*(1-x)^(5-i))
    }
    
    p <- seq(0,1,length=11)
    
    sums <- sapply(p,f)
    > sums
     [1] 1.0000 0.6643 0.4368 0.2923 0.2128 0.1875 0.2128
     [8] 0.2923 0.4368 0.6643 1.0000
    
  3. 2017-10-04 22:10

    I'd do something like this,

    p <- seq(0,1,length=11)
    i <- 0:5
    g <- function(a,i){
      a^i*(1-a)^(5-i)
    }
    
    plot(p, rowSums(outer(X = p, Y = i, FUN = g)))
    

    To answer your question, I don't think there is one correct way to do this; a more functional approach might be

    Reduce(function(s, x) s + g(p, x), x = 0:5, init=0)
    

    but it's likely to be less efficient, and arguably less readable.

Leave a reply to - Misunderstanding of functions in R

◀ Go back