To count number of occurences in columns of data frame in R, you can use table() function or count() function from dplyr package.

The following method shows how you can do it with syntax.

Method 1: Use table() Function

table(df)

Method 2: Use count() Function

library(dplyr)

count(df)

The following examples show how to count occurences in column of data frame in R.

Count Occurrences in Columns in R Using table() Function

Let’s see how we can use table() function to count number occurences in columns of data frame:

# Create dafaframe
df <- data.frame(Machine_name=c(NA,"B","C","D","E","F","G","H","A","B","A","C",NA,"B","E","H"),
                 Status=c("OK","Suspect",NA,"OK","Suspect","Suspect","Suspect","OK","OK","OK","OK","OK","Suspect","Suspect","Suspect","OK"))

# Count occurrences in a specific column
occurrences <- table(df$Machine_name)
print(occurrences)

# Count occurrences in all columns
occurrences1 <- apply(df, 2, table)
print(occurrences1)

Output:

A B C D E F G H 
2 3 2 1 2 1 1 2 

$Machine_name

A B C D E F G H 
2 3 2 1 2 1 1 2 

$Status

     OK Suspect 
      8       7 

Here the output shows count occurrences for Machine_name column and also for all column of data frame.

Count Number of Occurrences in Columns in R Using count() Function

Let’s see how we can use count() function to count number of occurrrences in columns of data frame in R:

# Create dafaframe
df <- data.frame(Machine_name=c(NA,"B","C","D","E","F","G","H","A","B","A","C",NA,"B","E","H"),
                 Status=c("OK","Suspect",NA,"OK","Suspect","Suspect","Suspect","OK","OK","OK","OK","OK","Suspect","Suspect","Suspect","OK"))

# Count occurrences in a specific column
occurrences <- df%>% count(Machine_name)
print(occurrences)

Output:

  Machine_name n
1            A 2
2            B 3
3            C 2
4            D 1
5            E 2
6            F 1
7            G 1
8            H 2
9         <NA> 2

The output shows count number of occurrences in Machine_name column of data frame.