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

R ProgrammingServer Side ProgrammingProgramming

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 −

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)

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
Published on 06-Nov-2021 07:06:00