2

Suppose I have the following dataset

set.seed(85)
a <- data.frame(replicate(10,sample(0:3,5,rep=TRUE)))

and I plot it in the following way:

library(ggplot2)
ggplot(stack(a), aes(x = values)) + 
  geom_bar()

From the graph I can read that there are a little less than 1250 occurrences of '3' in the dataset, but is there a way to output frequency of each x-axis value in the dataset as an independent list (i.e. not as numbers on the barplot)? I am looking for a list of how many occurrences of '3' there are in the dataset (and also for the values, 0, 1, & 2).

output:
0: 1249
1: 1200
2: ...
3: ...

Any help is much appreciated

Icewaffle
  • 443
  • 2
  • 13
  • 1
    do you want to plot the frequency table ? if so, you can look at https://stackoverflow.com/questions/12318120/adding-table-within-the-plotting-region-of-a-ggplot-in-r?answertab=active#tab-top – i94pxoe Mar 09 '20 at 15:29

1 Answers1

2

We can convert to 'long' format and then do the count

library(dplyr)
library(tidyr)
a %>%
   pivot_longer(everything()) %>% 
   count(value)

To get the barplot

library(ggplot2)
a %>% 
    pivot_longer(everything()) %>%
    count(value) %>% 
    ggplot(aes(x = value, y = n)) + 
        geom_bar(stat = 'identity')

In base R, unlist and get the table

table(unlist(a))

or for plotting

barplot(table(unlist(a)))
akrun
  • 874,273
  • 37
  • 540
  • 662