Reputation: 1433
I have a dataframe where I want to calculate a new row based on the two existing rows by multiplying them. The structure of my dataframe is as below:
structure(list(month = c("mazda", "yamaha", "car"), april = c(11,
12, 0.1), may = c(14, 15, 0.5)), row.names = c(NA, -3L), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), vars = "month", drop = TRUE, indices = list(
2L, 0L, 1L), group_sizes = c(1L, 1L, 1L), biggest_group_size = 1L, labels = structure(list(
month = c("car", "mazda", "yamaha")), row.names = c(NA, -3L
), class = "data.frame", vars = "month", drop = TRUE))
I want to add a row total
which would be a product of mazda
and car
. And if row car is not found it should be 0
in the new row total
.
Desired output I am trying to achieve :
# A tibble: 4 x 3
# Groups: month [4]
month april may
<chr> <dbl> <dbl>
1 mazda 11 14
2 yamaha 12 15
3 car 0.1 0.5
4 total 1.1 7
Upvotes: 0
Views: 460
Reputation: 50728
This really sounds/looks like an XY problem. I would advise rethinking your general code & data design. For example, why is column 1 labelled month
but then contains entries "mazda"
, "yamaha"
, "car"
and "total"
?
For what it's worth, you can reproduce your expected output with
rbind(df, c(month = "total", df[df$month == "mazda", -1] * df[df$month == "car", -1]))
## A tibble: 4 x 3
## Groups: month [4]
# month april may
# <chr> <dbl> <dbl>
#1 mazda 11 14
#2 yamaha 12 15
#3 car 0.1 0.5
#4 total 1.1 7
Upvotes: 1