在R中,如何计算数据框中列的百分比统计信息?(以百分比扩展的表函数)

use*_*rJT 30 r dataframe

这是一个简单的问题,但我无法弄清楚如何使用prop.table,我经常需要这个功能.

我有这样的数据

> library(ggplot2)

> #sample data(tips is a dataset within the ggplot2 package)
> head(tips,3)
  total_bill tip    sex smoker day   time size
1         17 1.0 Female     No Sun Dinner    2
2         10 1.7   Male     No Sun Dinner    3
3         21 3.5   Male     No Sun Dinner    3
> #how often there is a non-smoker
> table(tips$smoker)

 No Yes 
151  93 
> #how many subjects
> nrow(tips)
[1] 244
Run Code Online (Sandbox Code Playgroud)

我需要知道吸烟者与非吸烟者的百分比这样的事情(丑陋的代码):

> #percentage of smokers
> options(digits=2)
> transform(as.data.frame(table(tips$smoker)),percentage_column=Freq/nrow(tips)*100)
  Var1 Freq percentage_column
1   No  151                62
2  Yes   93                38
> 
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?

(更好的是,它会在一组列(我列举的)上执行此操作并且输出格式有点很好)(例如,吸烟者,白天和时间)

jor*_*ran 59

如果你想要简洁,你可能会喜欢:

prop.table(table(tips$smoker))
Run Code Online (Sandbox Code Playgroud)

如果你愿意,然后按100和圆缩放.或者更像您的确切输出:

tbl <- table(tips$smoker)
cbind(tbl,prop.table(tbl))
Run Code Online (Sandbox Code Playgroud)

如果你想为多个列做这个,你可以根据你的口味告诉你看起来干净的输出有很多不同的方向,但这里有一个选项:

tblFun <- function(x){
    tbl <- table(x)
    res <- cbind(tbl,round(prop.table(tbl)*100,2))
    colnames(res) <- c('Count','Percentage')
    res
}

do.call(rbind,lapply(tips[3:6],tblFun))
       Count Percentage
Female    87      35.66
Male     157      64.34
No       151      61.89
Yes       93      38.11
Fri       19       7.79
Sat       87      35.66
Sun       76      31.15
Thur      62      25.41
Dinner   176      72.13
Lunch     68      27.87
Run Code Online (Sandbox Code Playgroud)

如果你不喜欢将不同的表堆叠在一起,你可以do.call放弃并将它们留在列表中.


dig*_*All 10

你的代码对我来说似乎并不那么难看......
但是,另一种选择(不是更好)可能是:

df <- data.frame(table(yn))
colnames(df) <- c('Smoker','Freq')
df$Perc <- df$Freq / sum(df$Freq) * 100

------------------
  Smoker Freq Perc
1     No   19 47.5
2    Yes   21 52.5
Run Code Online (Sandbox Code Playgroud)