Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ``` r
- library(tidyverse)
- df <- tibble(x=1:100, y = rep(LETTERS[1:20],5) )
- df
- #> # A tibble: 100 × 2
- #> x y
- #> <int> <chr>
- #> 1 1 A
- #> 2 2 B
- #> 3 3 C
- #> 4 4 D
- #> 5 5 E
- #> 6 6 F
- #> 7 7 G
- #> 8 8 H
- #> 9 9 I
- #> 10 10 J
- #> # ℹ 90 more rows
- df_share <- df |>
- group_by(y) |>
- mutate(share=x/sum(x)) |>
- ungroup()
- df_share
- #> # A tibble: 100 × 3
- #> x y share
- #> <int> <chr> <dbl>
- #> 1 1 A 0.00488
- #> 2 2 B 0.00952
- #> 3 3 C 0.0140
- #> 4 4 D 0.0182
- #> 5 5 E 0.0222
- #> 6 6 F 0.0261
- #> 7 7 G 0.0298
- #> 8 8 H 0.0333
- #> 9 9 I 0.0367
- #> 10 10 J 0.04
- #> # ℹ 90 more rows
- sessionInfo()
- #> R version 4.4.2 (2024-10-31)
- #> Platform: x86_64-pc-linux-gnu
- #> Running under: Debian GNU/Linux 12 (bookworm)
- #>
- #> Matrix products: default
- #> BLAS: /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.11.0
- #> LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.11.0
- #>
- #> locale:
- #> [1] LC_CTYPE=en_GB.UTF-8 LC_NUMERIC=C
- #> [3] LC_TIME=en_GB.UTF-8 LC_COLLATE=en_GB.UTF-8
- #> [5] LC_MONETARY=en_GB.UTF-8 LC_MESSAGES=en_GB.UTF-8
- #> [7] LC_PAPER=en_GB.UTF-8 LC_NAME=C
- #> [9] LC_ADDRESS=C LC_TELEPHONE=C
- #> [11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C
- #>
- #> time zone: Europe/Brussels
- #> tzcode source: system (glibc)
- #>
- #> attached base packages:
- #> [1] stats graphics grDevices utils datasets methods base
- #>
- #> other attached packages:
- #> [1] lubridate_1.9.3 forcats_1.0.0 stringr_1.5.1 dplyr_1.1.4
- #> [5] purrr_1.0.2 readr_2.1.5 tidyr_1.3.1 tibble_3.2.1
- #> [9] ggplot2_3.5.1 tidyverse_2.0.0
- #>
- #> loaded via a namespace (and not attached):
- #> [1] gtable_0.3.5 compiler_4.4.2 reprex_2.1.0 tidyselect_1.2.1
- #> [5] scales_1.3.0 yaml_2.3.8 fastmap_1.1.1 R6_2.5.1
- #> [9] generics_0.1.3 knitr_1.46 munsell_0.5.1 R.cache_0.16.0
- #> [13] pillar_1.10.1.9000 tzdb_0.4.0 R.utils_2.12.3 rlang_1.1.4
- #> [17] utf8_1.2.4 stringi_1.8.4 xfun_0.43 fs_1.6.4
- #> [21] timechange_0.3.0 cli_3.6.3 withr_3.0.0 magrittr_2.0.3
- #> [25] digest_0.6.35 grid_4.4.2 hms_1.1.3 lifecycle_1.0.4
- #> [29] R.methodsS3_1.8.2 R.oo_1.26.0 vctrs_0.6.5 evaluate_0.23
- #> [33] glue_1.7.0 styler_1.10.3 colorspace_2.1-0 rmarkdown_2.26
- #> [37] tools_4.4.2 pkgconfig_2.0.3 htmltools_0.5.8.1
- ```
- <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