按R中的不同列值求和,忽略重复值
我希望计算一个和,忽略分类列中的重复值。以以下数据为例,受问题启发:按R中的不同列值求和,忽略重复值,r,R,我希望计算一个和,忽略分类列中的重复值。以以下数据为例,受问题启发: 在获得总和之前,我们可以使用unique进行包装 library(dplyr) other_shop %>% group_by(shop_id, shop_name) %>% mutate(shop_total_sale_goal = sum(unique(city_sale_goal), na.rm = TRUE), shop_profit = sum(profit, na
在获得
总和之前,我们可以使用unique
进行包装
library(dplyr)
other_shop %>%
group_by(shop_id, shop_name) %>%
mutate(shop_total_sale_goal = sum(unique(city_sale_goal), na.rm = TRUE),
shop_profit = sum(profit, na.rm = TRUE)) %>%
ungroup
-输出
# A tibble: 6 x 7
# shop_id shop_name city city_sale_goal profit shop_total_sale_goal shop_profit
# <dbl> <chr> <chr> <dbl> <dbl> <dbl> <dbl>
#1 1 Shop A London 12 3 21 7
#2 1 Shop A London 12 1 21 7
#3 1 Shop A Paris 9 3 21 7
#4 2 Shop B Cardiff 15 6 15 6
#5 3 Shop C Dublin 10 5 10 14
#6 3 Shop C Dublin 10 9 10 14
#一个tible:6 x 7
#店铺名称城市销售目标利润店铺总额销售目标店铺利润
#
#1 1 A店伦敦12 3 21 7
#2 1伦敦A店12 1 21 7
#3 1巴黎A店9 3 21 7
#4 2卡迪夫B店15 6 15 6
#5 3都柏林C店10 5 10 14
#都柏林3号店C 10 9 10 14
library(dplyr)
other_shop %>%
group_by(shop_id, shop_name) %>%
mutate(shop_total_sale_goal = sum(unique(city_sale_goal), na.rm = TRUE),
shop_profit = sum(profit, na.rm = TRUE)) %>%
ungroup
# A tibble: 6 x 7
# shop_id shop_name city city_sale_goal profit shop_total_sale_goal shop_profit
# <dbl> <chr> <chr> <dbl> <dbl> <dbl> <dbl>
#1 1 Shop A London 12 3 21 7
#2 1 Shop A London 12 1 21 7
#3 1 Shop A Paris 9 3 21 7
#4 2 Shop B Cardiff 15 6 15 6
#5 3 Shop C Dublin 10 5 10 14
#6 3 Shop C Dublin 10 9 10 14