Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count non zero entry in row in R

Tags:

r

I have following kind of data:

   mode1 mode2 mode3
1     8     1     0
2     0     0     0
3     6     5     4
4     1     2     3
5     1     1     1

Data using dput:

structure(list(mode1 = c(8L, 0L, 6L, 1L, 1L), mode2 = c(1L, 0L, 
5L, 2L, 1L), mode3 = c(0L, 0L, 4L, 3L, 1L)), class = "data.frame", row.names 
= c(NA,-5L))

I need to count number of non-zero entry in R. The problem I am facing is: all columns are in factor so if I convert to numeric then data values are changed.

Expected output:

   mode1 mode2 mode3 Count
1     8     1     0   2
2     0     0     0   0
3     6     5     4   3
4     1     2     3   3
5     1     1     1   3

Basically, count is a new column which counts number of non zero values row-wise. I tried length(xml_df[1,]!=0) but couldn't able to find answer.

like image 998
Saurabh Chauhan Avatar asked Mar 05 '23 10:03

Saurabh Chauhan


1 Answers

In base R

df$count <- rowSums(df!=0)
  mode1 mode2 mode3 count
1     8     1     0     2
2     0     0     0     0
3     6     5     4     3
4     1     2     3     3
5     1     1     1     3

Using dplyr

library(dplyr)
df %>% mutate(count=rowSums(.!=0))
#For specific columns we can use
df %>% mutate(count=rowSums(.[1:3]!=0))
#OR
df %>% mutate(count=rowSums(select(.,starts_with("mode"))!=0))
like image 101
A. Suliman Avatar answered Mar 16 '23 06:03

A. Suliman