如何获取R中所有行的每列的百分比值

How to get percentage value of each column across all rows in R

使用 R 的 tidyverse,如何获取行中每一列的 百分比 值?以 mpg 数据集为例,我尝试了以下代码:

new_mpg <- mpg %>%
  group_by(manufacturer, model) %>%
    summarise (n = n()) %>% 
      spread(model, n) %>% 
        mutate_if(is.integer, as.numeric)

new_mpg[,-1] %>% 
  mutate(sum = rowSums(.))

我希望创建以下输出:

manufacturer | 4runner4wd |     a4    | a4 quattro | a6 quattro | altima |
--------------------------------------------------------------------------
audi         |     NA     | 0.3888889 |   0.444444 | 0.166667   |   NA   |

然而,当我到达

new_mpg[,-1] %>% 
      mutate(sum = rowSums(.))

总和列returns NA。而且我无法计算 n()/sum。我只会得到NA。有什么解决办法吗?

正如@camille 在评论中提到的,您需要在 rowSums 调用中使用 na.rm = TRUE。要获取制造商中每个型号的百分比,您需要首先计算按制造商和型号分组的每个型号的数量,然后获取仅按制造商分组的百分比。 dplyr 这样做很聪明,因为它在 summarise 之后删除了一层分组,所以你只需要添加一个 mutate:

library(dplyr)
library(tidyr)
library(ggplot2)
new_mpg <- mpg %>%
  group_by(manufacturer, model) %>%
  summarise (n = n()) %>% 
  mutate(n = n/sum(n)) %>% 
  spread(model, n) %>% 
  mutate_if(is.integer, as.numeric)

new_mpg[,-1] %>% 
  mutate(sum = rowSums(., na.rm = TRUE))