I want to create a new column containg means of specific columns. The selected columns should depend on the group.
| group | first | second | third |
|---|---|---|---|
| 0 | 3 | 2 | 4 |
| 0 | 0 | NA | 5 |
| 0 | 2 | 7 | 1 |
| 1 | 3 | 1 | 6 |
| 1 | 4 | 0 | NA |
| 1 | 2 | 3 | 3 |
| 0 | 5 | 5 | 0 |
| 0 | 6 | 2 | 2 |
| 1 | NA | 1 | 3 |
As an example: I want a mean column with the following conditions:
- if a row contains a "0" in group, the mean should be calculated from "first" and "second"
- if a row contains a "1" in group, the mean should be calculated from "first" and "third"
- if a cell contains NA it should be ignored
So the final dataframe should look something like this:
| group | first | second | third | mean |
|---|---|---|---|---|
| 0 | 3 | 2 | 4 | 2.5 |
| 0 | 0 | NA | 5 | 0 |
| 0 | 2 | 7 | 1 | 4.5 |
| 1 | 3 | 1 | 6 | 4.5 |
| 1 | 4 | 0 | NA | 4 |
| 1 | 2 | 3 | 3 | 2.5 |
| 0 | 5 | 5 | 0 | 5 |
| 0 | 6 | 2 | 2 | 4 |
| 1 | NA | 1 | 3 | 3 |
Since my dataframe contains over 50 variables (and a few thousand rows) and not just those I want the mean from I can't select specific columns by their column or row number (like c(2,5),). I was thinking about adding a condition that explains to R that it should calculate the mean from "first" and "second" only for those rows that have a "0" in group and then the same principle for group = 1. I have no idea how to combinde these conditions or how I can do this in several steps.