输入数据示例如下:
set.seed(123)
filea <- data.frame(
ITEMS = c(rep("a",12),rep("b",12)),
MONTHS = c(seq(1,12),seq(1,12)),
VALUE = c(runif(12,0,50),runif(12,0,100))
)
需要创建一个新的列“percent_share”,该列具有该类别所有月份总和的百分比份额。
样本输出
PS:有100个项目
使用dplyr
您可以这样做:
library(dplyr)
set.seed(123)
filea <- data.frame(
ITEMS = c(rep("a",12),rep("b",12)),
MONTHS = c(seq(1,12),seq(1,12)),
VALUE = c(runif(12,0,50),runif(12,0,100))
)
filea = filea %>% group_by(ITEMS) %>% mutate(Percent_Share = VALUE/sum(VALUE)*100)
输出:
head(filea)
# A tibble: 6 x 4
# Groups: ITEMS [1]
ITEMS MONTHS VALUE Percent_Share
<fct> <int> <dbl> <dbl>
1 a 1 14.4 4.00
2 a 2 39.4 11.0
3 a 3 20.4 5.69
4 a 4 44.2 12.3
5 a 5 47.0 13.1
6 a 6 2.28 0.633