Вам вообще не нужно al oop
library(dplyr)
z <- data.frame(location = c("china", "china", "US", "US" ),
quantity = c(100, 200, 100, 200))
z %>% group_by(location) %>%
summarise(sum_quantity = quantity %>% sum) %>%
mutate(total = if_else(location == 'china',
sum_quantity,
sum_quantity * 3))
#> # A tibble: 2 x 3
#> location sum_quantity total
#> <fct> <dbl> <dbl>
#> 1 china 300 300
#> 2 US 300 900
# the ideal world
new_z <- data.frame(location = c("china", "china", "US", "US" ),
quantity = c(100, 200, 100, 200),
value_rate = c(1,1,3,3))
new_z %>% group_by(location) %>%
summarise(sum_quantity = (quantity * value_rate) %>% sum)
#> # A tibble: 2 x 2
#> location sum_quantity
#> <fct> <dbl>
#> 1 china 300
#> 2 US 900
Создано в 2020-01-07 пакетом Представить (v0.3.0)