Problem
I want to mutate my dataset based with a calculation based on a conditional without filtering that original dataset.
Example
Dataframe
df <- data.frame(amounts = c("2.95", "2.95", "14.95", "14.95",
"14.95", "-14.95", "-14.95", "-14.95", "-14.95"),
operation_code = c(100, 100, 101, 101, 101, 110, 110, 110, 110),
user_id = c(999, 111, 999, 111, 999, 111, 111, 999, 999))
This does the mutation I want but it filters by operation code == 110
. I want to keep all of the data from the data.frame and only populate fees
for the operation_type
110
.
df <- df %>%
group_by(user_id) %>%
filter(operation_code == 110) %>%
mutate(fees = n() * 20)
This is what the result should look like:
| amounts | operation_code | user_id | fees |
|---------|----------------|---------|------|
| 2.95 | 100 | 999 | NA |
| 2.95 | 100 | 111 | NA |
| 14.95 | 101 | 999 | NA |
| 14.95 | 101 | 111 | NA |
| 14.95 | 101 | 999 | NA |
| -14.95 | 110 | 111 | 40 |
| -14.95 | 110 | 111 | 40 |
| -14.95 | 110 | 999 | 40 |
| -14.95 | 110 | 999 | 40 |