How to find the number of non-empty values in an R data frame column?

R ProgrammingServer Side ProgrammingProgramming

To find the number of non-empty values, we can find the negation of the sum of empty values which is actually the total number of non-empty values. For example, if we have a data frame df that contains a column x which has some empty values then to find the total number of non-empty values we can find the opposite/negation of total empty values. This can be done with the help of sum function and negation operator as shown in the below examples.

Example1

Consider the below data frame −

Live Demo

> x<-sample(c(1,2,""),20,replace=TRUE)
> df1<-data.frame(x)
> df1

Output

   x
1  1
2  2
3  
4  
5  
6  
7  
8  2
9  
10
11 2
12 2
13 2
14 2
15 2
16
17
18
19
20 1

Finding total number of non-empty values in column x of df1 −

> sum(df1$x!="")

Output

[1] 9

Example2

Live Demo

> y<-sample(c(5,""),20,replace=TRUE)
> df2<-data.frame(y)
> df2

Output

   y
1  5
2  
3  5
4  
5  5
6  5
7  
8  5
9  5
10 5
11 5
12
13
14 5
15
16
17
18
19
20

Finding total number of non-empty values in column y of df2 −

> sum(df2$y!="")

Output

[1] 9

Example3

Live Demo

> z<-sample(c(5,3,2,""),20,replace=TRUE)
> df3<-data.frame(z)
> df3

Output

   z
1  5
2  3
3  
4  3
5  
6  
7  
8  3
9  2
10 2
11 2
12
13 2
14 2
15
16 3
17
18 2
19
20 3

Finding total number of non-empty values in column z of df3 −

> sum(df3$z!="")

Output

[1] 12
raja
Published on 05-Mar-2021 06:34:39
Advertisements