1

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?

Pentaquark
  • 53
  • 5

3 Answers3

3

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.

baptiste
  • 75,767
  • 19
  • 198
  • 294
2

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
zx8754
  • 52,746
  • 12
  • 114
  • 209
  • 1
    Thanks so much for responding! I think perhaps I wasn't clear which vector I need to map but `sapply` is definitely what I needed. – Pentaquark Oct 05 '17 at 15:34
2

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
John Coleman
  • 51,337
  • 7
  • 54
  • 119
  • Thanks so much! This is exactly the answer I needed. – Pentaquark Oct 05 '17 at 15:34
  • If I wanted to pass my function additional vectors, how would I go about that with `sapply`? For example, if I wanted to set the length of the `i` vector outside of the `function` and pass it as `function(x,i)`, what would be the proper way to do that? Trying `sapply(p,f(p,i))` would put me right back in the same boat. – Pentaquark Oct 05 '17 at 20:35