File: Expectation.R

package info (click to toggle)
r-cran-distr 2.9.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 2,344 kB
  • sloc: ansic: 199; sh: 13; makefile: 2
file content (40 lines) | stat: -rw-r--r-- 1,022 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
require(distr)
options("newDevice"=TRUE)

if(!isGeneric("E")) 
   setGeneric("E", 
         function(object, fun) standardGeneric("E"))

setMethod("E",
        signature(object = "AbscontDistribution", 
                    fun = "function"),
        function(object, fun){
            integrand <- function(x) fun(x) * d(object)(x)
            return(integrate(f = integrand,
                             lower = q.l(object)(0),
                             upper = q.l(object)(1))$value)
          })

setMethod("E",
          signature(object = "DiscreteDistribution", 
                    fun = "function"),
          function(object, fun){
            supp = support(object)
            return(sum(fun(supp) * d(object)(supp)))
          })



# Example
id <- function(x) x
sq <- function(x) x^2

# Expectation and Variance of Binom(6,0.5)
B <- Binom(6, 0.5)
E(B, id)
E(B, sq) - E(B, id)^2

# Expectation and Variance of Norm(1,1)
N <- Norm(1, 1)
E(N, id)
E(N, sq) - E(N, id)^2