简体   繁体   English

如何获取 R 中一组数据的频率和百分比?

[英]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 :我们还可以使用来自janitortabyl

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.

相关问题 如何在分类响应中汇总数据以获取R中每种响应类型的百分比? - How can I aggregate data with categorical responses to get the percentage of each response type in R? 如何将已经采用频率分布格式的数据输入到 R? - How can i enter a data that is already in a frequency distribution format to R? 如何基于现有数据在R中创建百分比表? - How can I create a percentage table in R based on existing data? 如何获得数据集中给定值的总体百分比 - How do I get the overall percentage of a giving value in a data set 给定一个大的 dataframe,我如何找到以百分比表示的字符频率? - How can I find the frequency of characters in percentage given a big dataframe? 如何在 R 的同一直方图上添加频率和百分比? - How to add frequency & percentage on the same histogram in R? 如何计算R中答案的频率? - How can I count the frequency of an answer in R? R中频率和百分比的表格 - A table with frequency and percentage in R 如何在R中的现有数据集中添加一个名为“百分比”的新列。百分比是下表中提到的6项考试的平均值? - How do I add a new column named “Percentage” to the existing data set in R.Percentage is the average of the 6 exams as mentioned in the table below? 如何获得调查package中频率表的百分比 - How to get the percentage of the frequency table in survey package
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM