Count non zero values in each column of R dataframe
In this article, we are going to count the number of non-zero data entries in the data using R Programming Language.
To check the number of non-zero data entries in the data first we have to put that data in the data frame by using:
data <- data.frame(x1 = c(1,2,0,100,0,3,10),
x2 = c(5,0,1,8,10,0,0),
x3 = 0)
print(data)
Output:
Now we have the data in the data frame. So, to count the number of non-zeroes entries in each column we use colSums() function. This function is used as:
colSums( data != 0)
Output:
As you can clearly see that there are 3 columns in the data frame and Col1 has 5 nonzeros entries (1,2,100,3,10) and Col2 has 4 non-zeroes entries (5,1,8,10) and Col3 has 0 non-zeroes entries.
Example 1: Here we are going to create a dataframe and then count the non-zero values in each column.
R
data <- data.frame (x1 = c (1,2,0,100,0,3,10),
x2 = c (5,0,1,8,10,0,0),
x3 = 0)
print (data)
colSums (data != 0)
|
Output:
Example 2: In this example, we are using iris3 dataset is used.
R
data <- data.frame (iris3)
dim (data)
colSums (data != 0)
|
Output:
Example 3: In this example, the state.x77 dataset is used.
R
data <- data.frame (state.x77)
dim (data)
colSums (data != 0)
|
Output:
Example 4: In this example, the USArrest dataset is used.
R
data <- data.frame (USArrest)
dim (data)
colSums (data != 0)
|
Output:
Last Updated :
24 Nov, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...