[英]How I can get frequency and percentage for a set of the data in R?
Here is a sample of the data这是数据示例
df<-read.table (text=" A1.1 A1.2 A1.3 A1.4 A1.5
3 3 4 3 1
0 4 1 2 4
4 1 0 4 3
1 2 3 3 3
4 4 3 3 3
1 3 0 1 4
0 1 3 0 0
1 1 0 0 1
", header=TRUE)
The outcome is结果是
Score Freq Percent
0 8 20
1 10 25
2 2 5
3 12 30
4 8 20
Total 40 100
I want to get the frequency and percentage for each score.我想获得每个分数的频率和百分比。 For example, 0 appears 8 times, so frequency= 8 and percentage= 8/40*100= 20 Assume that I have a large matrix.
例如,0 出现了 8 次,所以 frequency= 8 and percentage= 8/40*100= 20 假设我有一个大矩阵。 Is there a simple code to get this outcome?
是否有一个简单的代码来获得这个结果?
We could also use tabyl
from janitor
:我们还可以使用来自
janitor
的tabyl
:
library(janitor)
df |>
unlist() |>
tabyl() |>
adorn_totals("row") |>
adorn_pct_formatting()
Output: Output:
unlist(df) n percent
0 8 20.0%
1 10 25.0%
2 2 5.0%
3 12 30.0%
4 8 20.0%
Total 40 100.0%
Here这里
df2=data.frame(table(unlist(df)))
df2$Percent=df2$Freq/sum(df2$Freq)*100
Var1 Freq Percent
1 0 8 20
2 1 10 25
3 2 2 5
4 3 12 30
5 4 8 20
Using prop.table :使用prop.table :
x <- table(unlist(df))
data.frame(x, prop.table(x) * 100)
# Var1 Freq Var1.1 Freq.1
# 1 0 8 0 20
# 2 1 10 1 25
# 3 2 2 2 5
# 4 3 12 3 30
# 5 4 8 4 20
Solution using dplyr (Tidyverse):使用 dplyr (Tidyverse) 的解决方案:
df %>%
unlist() %>%
as_tibble() %>%
count(value) %>%
mutate(share = n / sum(n))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.