我有一个这样的数据库:
Year Type Return
1900 A 4
1900 B 7
1901 A 87
1901 B 3
1902 A 9.7
1902 B 2
我想将返回绝对值转换为年度百分比。
例如。对于1900年,我想要:
4/(4+7) = 0,36
7/(4+7) = 0,64
和:
Year Type Return
1900 A 36%
1900 B 64%
真正的数据库有
如果Type始终是seqA, B
:
df <- data.frame(data.table::fread("Year Type Return
1900 A 4
1900 B 7
1901 A 87
1901 B 3
1902 A 9.7
1902 B 2"))
library(tidyverse)
df %>%
group_by(Year) %>%
summarise(Return = Return / sum(Return)) %>%
ungroup() %>%
mutate(Type = df$Type) %>%
relocate(Year, Type, Return) %>%
mutate(Return = round(Return, 2))
Year Type Return
<int> <chr> <dbl>
1 1900 A 0.36
2 1900 B 0.64
3 1901 A 0.97
4 1901 B 0.03
5 1902 A 0.83
6 1902 B 0.17
df %>%
group_by(Year) %>%
summarise(Return = Return / sum(Return)) %>%
ungroup() %>%
mutate(Type = df$Type) %>%
relocate(Year, Type, Return) %>%
mutate(Return = scales::percent(Return))
Year Type Return
<int> <chr> <chr>
1 1900 A 36%
2 1900 B 64%
3 1901 A 97%
4 1901 B 3%
5 1902 A 83%
6 1902 B 17%