How to sum elements of each row in a df based on a condition

``````df <- data.frame(
A = c(2,1,2,0,0,1),
B = c(4,5,3,0,1,3),
C = c(1,0,2,0,7,4),
D = c(3,2,1,0,0,0)
)
row.names(df) <- c('one','two','three', 'four', 'five', 'six')
df

A B C D
one   2 4 1 3
two   1 5 0 2
three 2 3 2 1
four  0 0 0 0
five  0 1 7 0
six   1 3 4 0
``````

Hi I would like to count the number of elements in each row that are not 0, and store it as a new data frame with one column and the same number of rows as the original. If I did this the solution would look like this:

``````      A
one   4
two   3
three 4
four  0
five  2
six   3
``````

???? Thanks!!!

I am sure there is a tidyverse way to do this also.

``````DF <- data.frame(
A = c(2,1,2,0,0,1),
B = c(4,5,3,0,1,3),
C = c(1,0,2,0,7,4),
D = c(3,2,1,0,0,0)
)
row.names(DF) <- c('one','two','three', 'four', 'five', 'six')
DF
#>       A B C D
#> one   2 4 1 3
#> two   1 5 0 2
#> three 2 3 2 1
#> four  0 0 0 0
#> five  0 1 7 0
#> six   1 3 4 0

MyFunc <- function(x) sum(x != 0)
OutDF <- data.frame(A = apply(DF, 1, MyFunc))
OutDF
#>       A
#> one   4
#> two   3
#> three 4
#> four  0
#> five  2
#> six   3
``````

Created on 2020-05-27 by the reprex package (v0.3.0)

Thanks I solved it!

Just rowSums I think::

`DF2 <- rowSums(DF != 0)`

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.