I want to transform this df such that the total is only the product of A and B, not including C
df <- data.frame(id = c(1, 1, 1, 1, 2, 2, 2, 2), type = c('A', 'B', 'C', 'total', 'A', 'B', 'C', 'total'), value = c('1', NA, '4', NA, '5', '4', '8', NA))
id type value
1 A 1
1 B <NA>
1 C 4
1 total <NA>
2 A 5
2 B 4
2 C 8
2 total <NA>
The result should look something like:
df_result <- data.frame(id = c(1, 1, 1, 1, 2, 2, 2, 2), type = c('A', 'B', 'C', 'total', 'A', 'B', 'C', 'total'), value = c('1', NA, '4', '1', '5', '4', '8', '20'))
id type value
1 A 1
1 B <NA>
1 C 4
1 total 1
2 A 5
2 B 4
2 C 8
2 total 20
My code so far does the product of all of the types, not just A and B:
df %>%
group_by(id) %>%
mutate(
value = as.numeric(value),
value = if_else(type == 'total', prod(value, na.rm = T), value)
)
extra: what if the id does not uniquely identify one 'set' of types? e.g.
df2 <- data.frame(id = c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2), type = c('A', 'B', 'C', 'total', 'A', 'B', 'C', 'total', 'A', 'B', 'C', 'total'), value = c('1', NA, '4', NA, '2', NA, '4', NA, '5', '4', '8', NA))
id type value
1 A 1
1 B <NA>
1 C 4
1 total <NA>
1 A 2
1 B <NA>
1 C 4
1 total <NA>
2 A 5
2 B 4
2 C 8
2 total <NA>
The totals above would be 1, 2 and 20 respectively.
Thanks for all the help!