R Count Number of Non-Zero Values in Each Data Frame Column (Example Code)

In this R programming tutorial you’ll learn how to count non-zeros in vectors and data frame columns.

Creation of Example Data

set.seed(926342)           # Constructing example data
my_df <- data.frame(matrix(sample(0:3, 20, replace = TRUE), ncol = 5))
my_df                      # Showing example data in RStudio console
#   X1 X2 X3 X4 X5
# 1  2  1  2  0  1
# 2  2  0  1  1  0
# 3  3  2  2  0  0
# 4  2  0  1  3  0

Example: Counting Non-Zero Values in Data Frame Variables Using colSums() Function

colSums(my_df != 0)        # Counting non-zero values in each column
# X1 X2 X3 X4 X5 
#  4  2  4  2  1

2 Comments. Leave new

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top