rstatisticscovariance# Implementing covariance by hand

I made a curious observation today - I implemented the covariance of two vectors 3 different ways, and got 2 different answers. In R, methods 1 and 2 are the same. Method 3 ought to be mathematically the same, but somehow it returns a different number. What is the bug here?

```
# Make some data
set.seed(100)
n = 100
foo = rnorm(n)
bar = rnorm(n)
# method 1
cov(foo, bar)
# method 2
sum(
(foo - mean(foo)) * (bar - mean(bar))
) / (n-1)
# method 3
(
sum(foo*bar) -
mean(bar)*sum(foo) -
mean(foo)*sum(bar) +
mean(foo)*mean(bar)
) / (n-1)
```

Solution

You forgot that the *mathematical* expression `sum_{i=1}^n mean(foo)*mean(bar)`

comes out to `n*mean(foo)*mean(bar)`

, not `mean(foo)*mean(bar)`

...

```
(sum(foo*bar) -
mean(bar)*sum(foo) -
mean(foo)*sum(bar) + n*mean(foo)*mean(bar))/(n-1)
```

- Overlay points on top of violin plot
- Add percentage labels to geom_col()
- How to place a js inside a swiper with appendTo()?
- How to make a single plot from two dataframes with ggplot2
- Error in installing "TopicModels" package in Google Colab
- Identify connected subnetworks (R-igraph)
- Adding labels to geom_col()
- Legend title in ggplot2
- How can I extract a value from a dataframe based on values within that dataframe?
- R list files with multiple conditions
- R - getting count of maximum-sized sub-group when summarising at prior group_by level
- Problems when running GDC_prepare in R
- Filtering files with names starting with a specific string
- Mutate a vector within a pipe chain
- How to sum a variable by group
- Using hex code to change text color in RMarkdown PDF (R)
- How to Remove Degree and Cardinal Direction Symbols from ggplot Coordinate Axes
- rstan and brms cause R and RStudio session abort
- How to change the plot background color generated by plot(effect(...)) in grey with white grid in R？
- SQL query on arrow duckdb workflow in R
- Venn diagram with duplicated elements
- R- Filter by time closest to midnight
- Difference between rlm() and lm_robust
- Is there a way to combine sorting an rhandsontable and removing from an rhandsontable?
- Split violin plot with ggplot2
- ggbarplot top of one bar does not align with its error bar
- read file from google drive
- Placing text into stacked bar charts in ggplot
- R - windowing data backwards from latest data in non-overlapping (not-rolling) periods and counting within periods
- Replacing list elements while preserving their attributes