larry77

group_by

Jan 1st, 2025
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.83 KB | None | 0 0
  1. ``` r
  2. library(tidyverse)
  3.  
  4.  
  5. df <- tibble(x=1:100, y = rep(LETTERS[1:20],5) )
  6.  
  7. df
  8. #> # A tibble: 100 × 2
  9. #> x y
  10. #> <int> <chr>
  11. #> 1 1 A
  12. #> 2 2 B
  13. #> 3 3 C
  14. #> 4 4 D
  15. #> 5 5 E
  16. #> 6 6 F
  17. #> 7 7 G
  18. #> 8 8 H
  19. #> 9 9 I
  20. #> 10 10 J
  21. #> # ℹ 90 more rows
  22.  
  23. df_share <- df |>
  24. group_by(y) |>
  25. mutate(share=x/sum(x)) |>
  26. ungroup()
  27.  
  28. df_share
  29. #> # A tibble: 100 × 3
  30. #> x y share
  31. #> <int> <chr> <dbl>
  32. #> 1 1 A 0.00488
  33. #> 2 2 B 0.00952
  34. #> 3 3 C 0.0140
  35. #> 4 4 D 0.0182
  36. #> 5 5 E 0.0222
  37. #> 6 6 F 0.0261
  38. #> 7 7 G 0.0298
  39. #> 8 8 H 0.0333
  40. #> 9 9 I 0.0367
  41. #> 10 10 J 0.04
  42. #> # ℹ 90 more rows
  43.  
  44. sessionInfo()
  45. #> R version 4.4.2 (2024-10-31)
  46. #> Platform: x86_64-pc-linux-gnu
  47. #> Running under: Debian GNU/Linux 12 (bookworm)
  48. #>
  49. #> Matrix products: default
  50. #> BLAS: /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.11.0
  51. #> LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.11.0
  52. #>
  53. #> locale:
  54. #> [1] LC_CTYPE=en_GB.UTF-8 LC_NUMERIC=C
  55. #> [3] LC_TIME=en_GB.UTF-8 LC_COLLATE=en_GB.UTF-8
  56. #> [5] LC_MONETARY=en_GB.UTF-8 LC_MESSAGES=en_GB.UTF-8
  57. #> [7] LC_PAPER=en_GB.UTF-8 LC_NAME=C
  58. #> [9] LC_ADDRESS=C LC_TELEPHONE=C
  59. #> [11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C
  60. #>
  61. #> time zone: Europe/Brussels
  62. #> tzcode source: system (glibc)
  63. #>
  64. #> attached base packages:
  65. #> [1] stats graphics grDevices utils datasets methods base
  66. #>
  67. #> other attached packages:
  68. #> [1] lubridate_1.9.3 forcats_1.0.0 stringr_1.5.1 dplyr_1.1.4
  69. #> [5] purrr_1.0.2 readr_2.1.5 tidyr_1.3.1 tibble_3.2.1
  70. #> [9] ggplot2_3.5.1 tidyverse_2.0.0
  71. #>
  72. #> loaded via a namespace (and not attached):
  73. #> [1] gtable_0.3.5 compiler_4.4.2 reprex_2.1.0 tidyselect_1.2.1
  74. #> [5] scales_1.3.0 yaml_2.3.8 fastmap_1.1.1 R6_2.5.1
  75. #> [9] generics_0.1.3 knitr_1.46 munsell_0.5.1 R.cache_0.16.0
  76. #> [13] pillar_1.10.1.9000 tzdb_0.4.0 R.utils_2.12.3 rlang_1.1.4
  77. #> [17] utf8_1.2.4 stringi_1.8.4 xfun_0.43 fs_1.6.4
  78. #> [21] timechange_0.3.0 cli_3.6.3 withr_3.0.0 magrittr_2.0.3
  79. #> [25] digest_0.6.35 grid_4.4.2 hms_1.1.3 lifecycle_1.0.4
  80. #> [29] R.methodsS3_1.8.2 R.oo_1.26.0 vctrs_0.6.5 evaluate_0.23
  81. #> [33] glue_1.7.0 styler_1.10.3 colorspace_2.1-0 rmarkdown_2.26
  82. #> [37] tools_4.4.2 pkgconfig_2.0.3 htmltools_0.5.8.1
  83. ```
  84.  
  85. <sup>Created on 2025-01-01 with [reprex v2.1.0](https://reprex.tidyverse.org)</sup>
Advertisement
Add Comment
Please, Sign In to add comment