Home > Mobile >  How I can get frequency and percentage for a set of the data in R?
How I can get frequency and percentage for a set of the data in R?

Time:11-18

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. Is there a simple code to get this outcome?

CodePudding user response:

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

CodePudding user response:

We could also use tabyl from janitor:

library(janitor)

df |> 
  unlist() |>
  tabyl() |>
  adorn_totals("row") |>
  adorn_pct_formatting()

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%

CodePudding user response:

Using 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

CodePudding user response:

Solution using dplyr (Tidyverse):

df %>% 
  unlist() %>% 
  as_tibble() %>% 
  count(value) %>% 
  mutate(share = n / sum(n))
  •  Tags:  
  • r
  • Related