【问题标题】:Transform absolute values into yearly percentages in R [duplicate]将绝对值转换为 R 中的年度百分比 [重复]
【发布时间】:2021-12-16 20:18:16
【问题描述】:

我有一个这样的数据库:

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%

真正的数据库有 >10k 行。

【问题讨论】:

  • 库(dplyr); Df %>% group_by(year) %>% mutate(res = return/sum(return))。如果您想要报告的百分比,您可以添加 * 100;如果您想进一步分析更易于使用的比率。 Df 是包含数据的数据框。

标签: r percentage


【解决方案1】:

如果 Type 始终是 seq A,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% 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多