How to count the number of times a value occurs in a column of an R data frame?



To count the number of times a value occurs in a column of an R data frame, we can use table function for that particular column.

For example, if we have a data frame called df that contains a column say Response then finding the number of times a value occurs in Response can be found by using the command given below −

table(df$Response)

Example 1

Following snippet creates a sample data frame −

x<-rpois(20,1) df1<-data.frame(x) df1

Output

The following dataframe is created −

   x 1  1 2  2 3  1 4  5 5  0 6  0 7  0 8  0 9  0 10 2 11 3 12 1 13 0 14 2 15 1 16 0 17 4 18 0 19 2 20 1

To create a table for data in x, add the following code to the above snippet −

x<-rpois(20,1) df1<-data.frame(x) table(df1$x)

Output

If you execute all the above given codes as a single program, it generates the following output −

0 1 2 3 4 5 8 5 4 1 1 1

Example 2

Following snippet creates a sample data frame −

y<-round(rnorm(20,5,2),0) df2<-data.frame(y) df2

Output

The following dataframe is created −

   y 1  8 2  3 3  6 4  6 5  5 6  6 7  5 8  8 9  6 10 6 11 5 12 5 13 10 14 3 15 8 16 5 17 6 18 6 19 4 20 8

To create a table for data in y, add the following code to the above snippet −

y<-round(rnorm(20,5,2),0) df2<-data.frame(y) table(df2$y)

Output

If you execute all the above given codes as a single program, it generates the following output −

 3 4 5 6 8 10 2 1 5 7 4  1

Example 3

Following snippet creates a sample data frame −

z<-round(rnorm(20,25,1),0) df3<-data.frame(z) df3

Output

The following dataframe is created −

   z 1  24 2  25 3  24 4  26 5  24 6  25 7  25 8  27 9  26 10 26 11 23 12 25 13 24 14 24 15 27 16 26 17 25 18 26 19 25 20 26

To create table for data in z, add the following code to the above snippet −

z<-round(rnorm(20,25,1),0) df3<-data.frame(z) table(df3$z)

Output

If you execute all the above given codes as a single program, it generates the following output −

23 24 25 26 27 1   5  6 6  2
Updated on: 2021-11-06T07:06:00+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements