R 按列将数据table 转换为百分比table

R Convert a datatable into percentage table columnwise

我正在尝试将此 table 转换为百分比 table 列。

Class 2021 年 1 月 2021 年 2 月
一个 50 100
B 50 150
C 100 100

我期待这个 table。

Class 2021 年 1 月 2021 年 2 月
一个 25% 28.57%
B 25% 42.86%
C 50% 28.57%
x <- data.frame(class = c("A", "B", "C"),
                Jan2021 = c(50,50,100),
                Feb2021 = c(100,150,100))

我可以做到这一点,但我有很多 columns/rows 不同的名字。有没有更简单的方法来计算每列的百分比?

x_pct = mutate(x, 
            Jan_pct = Jan2021 / sum(Jan2021) *100,
            Feb_pct = Feb2021 / sum(Feb2021) *100)

您可以使用 dplyr::mutate_if()scales::percent:

x %>% 
  mutate_if(endsWith(names(.),"2021"),function(x) x / sum(x)) %>% 
  mutate_if(endsWith(names(.),"2021"),scales::percent, accuracy = 0.01)

输出:

  class Jan2021 Feb2021
1     A  25.00%  28.57%
2     B  25.00%  42.86%
3     C  50.00%  28.57%

你可以使用across-

library(dplyr)

x %>%  mutate(across(-class, ~paste(round(prop.table(.) * 100, 2), '%')))

#  class Jan2021 Feb2021
#1     A    25 % 28.57 %
#2     B    25 % 42.86 %
#3     C    50 % 28.57 %

lapply 以 R 为基数 -

x[-1] <- lapply(x[-1], function(x) paste(round(prop.table(x) * 100, 2), '%'))
library(janitor)
x %>%
  adorn_percentages("col") %>%
  adorn_pct_formatting(digits = 2)


 class Jan2021 Feb2021
     A  25.00%  28.57%
     B  25.00%  42.86%
     C  50.00%  28.57%