我有一个数据框,我想通过将两个现有行相乘来计算新行。我的数据框的结构如下:
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))
我想添加一行total
,该行将是mazda
和car
的乘积。并且如果未找到行车,它应该位于新行0
中的total
。
我想要达到的期望输出:
# 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
答案 0 :(得分:1)
这听起来确实/看起来像是XY问题。我建议您重新考虑一下您的常规代码和数据设计。例如,为什么第1列标记为month
,却又包含条目"mazda"
,"yamaha"
,"car"
和"total"
?
对于它的价值,您可以使用来重现您的预期输出
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