# How to find the number of values in a column of an R data frame that are not zero?

If an R data frame has numerical columns then it is also possible that there exist zeros in few or all columns and we might be interested in finding the number of non-zero values in a column. This will help us to compare the columns based on the number on non-zero values and it can be done by using colSums.

## Example

Consider the below data frame −

Live Demo

x1<-sample(0:10,20,replace=TRUE)
x2<-sample(0:50,20,replace=TRUE)
x3<-sample(0:5,20,replace=TRUE)
x4<-sample(0:15,20,replace=TRUE)
x5<-sample(0:20,20,replace=TRUE)
df1<-data.frame(x1,x2,x3,x4,x5)
df1

## Output

  x1 x2 x3 x4 x5
1  9 47 4  1  6
2  7 6  1  7  7
3  3 20 5 15 19
4 10 13 2 13 13
5  10 49 1 8 12
6  10 49 1 2  1
7  9  36 5 2 15
8  0  27 4 15 8
9  6  50 2 7 15
10 7  11 0 10 4
11 9  22 1  7 14
12 5  47 5  3 20
13 3  36 2  0  6
14 10 44 4  6 18
15 1  40 2  11 4
16 1  46 0  15 5
17 3  36 5  0  9
18 2  1  5  6 19
19 9  38 3  4  1
20 1  37 4 11 18

Finding the number of values in each column that are not zero −

## Example

colSums(df1!=0)

## Output

x1 x2 x3 x4 x5
19 20 18 18 20

Let’s have a look at another example −

## Example

Live Demo

y1<-rpois(20,1)
y2<-rpois(20,2)
y3<-sample(0:1,20,replace=TRUE)
y4<-sample(0:2,20,replace=TRUE)
df2<-data.frame(y1,y2,y3,y4)
df2

## Output

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

## Example

colSums(df2!=0)

## Output

y1 y2 y3 y4
15 19 8 13

Updated on: 08-Sep-2020

151 Views