2

Given the following data.frame, A:

         V1       V2        V3        V4        V5        V6
1 0.0000000 0.000000 0.0000000 0.1816416 0.0000000 0.1796779
2 0.1889351 0.000000 0.0000000 0.0000000 0.0000000 0.0000000
3 0.0000000 0.000000 0.1539683 0.0000000 0.0000000 0.1983812
4 0.0000000 0.155489 0.1869410 0.0000000 0.0000000 0.0000000
5 0.0000000 0.000000 0.0000000 0.0000000 0.1739382 0.0000000

How would I create a new column that counts the number of non-zero valued entries in row? Desired output:

         V1       V2        V3        V4        V5        V6  full_tally
1 0.0000000 0.000000 0.0000000 0.1816416 0.0000000 0.1796779  2
2 0.1889351 0.000000 0.0000000 0.0000000 0.0000000 0.0000000  1
3 0.0000000 0.000000 0.1539683 0.0000000 0.0000000 0.1983812  2
4 0.0000000 0.155489 0.1869410 0.0000000 0.0000000 0.0000000  2
5 0.0000000 0.000000 0.0000000 0.0000000 0.1739382 0.0000000  1

Code to create toy data.frame:

set.seed(1)
a = runif(n=30, min=0, max=0.2)
a[a<0.15] = 0
A = as.data.frame(matrix(a,              
           nrow=5,         
           ncol=6,         
           byrow = TRUE))

I tried something along the lines of:

A %>% mutate(full_tally = sum(V1:V6 > 0))

but it only looks at the first column's value for each row.

user2205916
  • 3,196
  • 11
  • 54
  • 82
  • 3
    This is very similar to https://stackoverflow.com/questions/37801338/r-count-nas-per-row-in-dataframe or for dplyr specifically - https://stackoverflow.com/questions/35443115/add-a-column-with-count-of-nas-and-mean-in-r-with-dplyr?noredirect=1&lq=1 – thelatemail Apr 03 '19 at 22:20

1 Answers1

3

Not a dplyr solution, but works well.

A$full_tally <- rowSums(A != 0)

A
#          V1       V2        V3        V4        V5        V6 full_tally
# 1 0.0000000 0.000000 0.0000000 0.1816416 0.0000000 0.1796779          2
# 2 0.1889351 0.000000 0.0000000 0.0000000 0.0000000 0.0000000          1
# 3 0.0000000 0.000000 0.1539683 0.0000000 0.0000000 0.1983812          2
# 4 0.0000000 0.155489 0.1869410 0.0000000 0.0000000 0.0000000          2
# 5 0.0000000 0.000000 0.0000000 0.0000000 0.1739382 0.0000000          1
www
  • 38,575
  • 12
  • 48
  • 84