R: How to Get a Sum of Two Distributions

R: How to get a sum of two distributions?

You probably want something like:

rowSums(expand.grid(A1, B1))

Using expand.grid will get you a dataframe of all combinations of A1 and B1, and rowSums will add them.

How to sample from a sum of two distributions: binomial and poisson

An alternative is to substitute the Binomial with a Poisson, and use Poisson additivity:

BH_model_block <- "
data{
int y;
int a;
}

parameters{
real <lower = 0, upper = 1> c;
real <lower = 0, upper = 1> b;
}

model{
y ~ poisson(a * b + c);
}
"

This differs in that if b is not small, the Binomial has a lower variance than the Poisson, but maybe there is overdispersion anyhow?

sum count across multiple variables

We can use mutate after grouping by 'id', 'date'

library(dplyr)
eg_data <- eg_data %>%
group_by(id, date) %>%
mutate(TotalSum = sum(sales))

Or with ave

eg_data$TotalSum = with(eg_data, ave(sales, id, date, FUN = sum))

How to calculate the sum of two normal distributions

The sum of two normal distributions is itself a normal distribution:

N(mean1, variance1) + N(mean2, variance2) ~ N(mean1 + mean2, variance1 + variance2)

This is all on wikipedia page.

Be careful that these really are variances and not standard deviations.

// X + Y
public static Gauss operator + (Gauss a, Gauss b) {
//NOTE: this is valid if X,Y are independent normal random variables
return new Gauss(a.mean + b.mean, a.variance + b.variance);
}

// X*b
public static Gauss operator * (Gauss a, double b) {
return new Gauss(a.mean*b, a.variance*b*b);
}


Related Topics



Leave a reply



Submit