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
Make Legend Invisible But Keep Figure Dimensions and Margins the Same
Cant Create File Name with Time Stamp
Dist Function with Large Number of Points
Difference of Two Character Vectors with Substring
R/Ggplot Cumulative Sum in Histogram
R - Calculate Test Mse Given a Trained Model from a Training Set and a Test Set
Error:Could Not Find Build Tools Necessary to Build
How to Avoid Density Curve Getting Cut Off in Plot
R - Random Forest and More Than 53 Categories
Why "Character Is Often Preferred to Factor" in Data.Table for Key
Get First Entries in Rows of List
Filtering a Dataframe Showing Only Duplicates
Rolling by Group in Data.Table R
Population Pyramid Plot with Ggplot2 and Dplyr (Instead of Plyr)