我有这样的数据集:
df = data.frame(group = c(rep('A',4), rep('B',3)),
subgroup = c('a', 'b', 'c', 'd', 'a', 'b', 'c'),
value = c(1,4,2,1,1,2,3))
group | subgroup | value
------------------------
A | a | 1
A | b | 4
A | c | 2
A | d | 1
B | a | 1
B | b | 2
B | c | 3
Run Code Online (Sandbox Code Playgroud)
我想要的是获得每个组中每个子组的值的百分比,即输出应该是:
group | subgroup | percent
------------------------
A | a | 0.125
A | b | 0.500
A | c | 0.250
A | d | 0.125
B | a | 0.167
B | b | 0.333
B | c | 0.500
Run Code Online (Sandbox Code Playgroud)
组A,子组A的示例:值为1,整个组A的总和为8(a = 1,b = 4,c = 2,d = 1) - 因此1/8 = 0.125
到目前为止,我只找到相当简单集合体喜欢这样,但我不能弄清楚如何"由亚组内的总和鸿沟"的部分来做的.
Ric*_*ven 32
根据您的评论,如果子组是唯一的,您可以这样做
library(dplyr)
group_by(df, group) %>% mutate(percent = value/sum(value))
# group subgroup value percent
# 1 A a 1 0.1250000
# 2 A b 4 0.5000000
# 3 A c 2 0.2500000
# 4 A d 1 0.1250000
# 5 B a 1 0.1666667
# 6 B b 2 0.3333333
# 7 B c 3 0.5000000
Run Code Online (Sandbox Code Playgroud)
或者要删除value
列并同时添加percent
列,请使用transmute
group_by(df, group) %>% transmute(subgroup, percent = value/sum(value))
# group subgroup percent
# 1 A a 0.1250000
# 2 A b 0.5000000
# 3 A c 0.2500000
# 4 A d 0.1250000
# 5 B a 0.1666667
# 6 B b 0.3333333
# 7 B c 0.5000000
Run Code Online (Sandbox Code Playgroud)
Ron*_*hah 11
我们可以用来prop.table
计算百分比/比率。
基础 R :
transform(df, percent = ave(value, group, FUN = prop.table))
# group subgroup value percent
#1 A a 1 0.125
#2 A b 4 0.500
#3 A c 2 0.250
#4 A d 1 0.125
#5 B a 1 0.167
#6 B b 2 0.333
#7 B c 3 0.500
Run Code Online (Sandbox Code Playgroud)
dplyr
:
library(dplyr)
df %>% group_by(group) %>% mutate(percent = prop.table(value))
Run Code Online (Sandbox Code Playgroud)
data.table
:
library(data.table)
setDT(df)[, percent := prop.table(value), group]
Run Code Online (Sandbox Code Playgroud)