r - 在 R 中查找汇总列的相对频率

我需要获取 R 中汇总列的相对频率。我使用 dplyr 的汇总来查找每个分组行的总数,如下所示:

data %>%
  group_by(x) %>%
  summarise(total = sum(dollars))

     x                    total 
   <chr>                 <dbl>
 1 expense 1              3600 
 2 expense 2              2150 
 3 expense 3              2000 

但现在我需要为每个总行的相对频率创建一个新列以获得此结果:

     x                   total     p
   <chr>                 <dbl>   <dbl>
 1 expense 1              3600   46.45%
 2 expense 2              2150   27.74%
 3 expense 3              2000   25.81%

我已经试过了:

data %>%
  group_by(x) %>%
  summarise(total = sum(dollars), p = scales::percent(total/sum(total))

还有这个:

data %>%
  group_by(x) %>%
  summarise(total = sum(dollars), p = total/sum(total)*100)

但结果总是这样:

     x                   total     p
   <chr>                 <dbl>   <dbl>
 1 expense 1              3600    100%
 2 expense 2              2150    100%
 3 expense 3              2000    100%

问题似乎是可能影响结果的汇总总计列。有什么想法可以帮助我吗?谢谢

最佳答案

由于分组,您得到 100%。但是,在您总结之后,dplyr 将放弃一级分组。意思是如果你例如执行 mutate() 之后,您将获得所需的结果:

library(dplyr)

data <- tibble(
  x = c("expense 1", "expense 2", "expense 3"),
  dollars = c(3600L, 2150L, 2000L)
)


data %>%
  group_by(x) %>%
  summarise(total = sum(dollars)) %>% 
  mutate(p = total/sum(total)*100)


# A tibble: 3 x 3
  x         total     p
  <chr>     <int> <dbl>
1 expense 1  3600  46.5
2 expense 2  2150  27.7
3 expense 3  2000  25.8

https://stackoverflow.com/questions/70525899/

相关文章:

node.js - 带有 Webpack 的 Electron 原生 NodeJS 模块

python - 如何解析 (1045, "Access denied for user ' Use

haskell - 如何为自定义数据类型定义 (+) 函数?

c++ - 即使在手动设置显示环境变量后,WSL Ubuntu 仍显示 "Error: Unable

r - 是否可以将变量从全局环境移动到单独的环境中?

android - Appium 创建 session 失败

() takes ">python - 为什么在我给出位置参数时 lambda 返回 "() takes

javascript - 一键执行两个功能

c# - Entity Framework 排序列表

c++ - 使用 C++ 生成真正的随机数 (Windows 10 x64)