0

I have the following dataframe:

      xxx2  xxx3  xxx5  xxx6  xxx7
3000  0.12  0.14  0.17    NA  1.42
3001    NA    NA    NA    NA    NA
3002    NA    NA    NA    NA    NA
3003  0.11  0.13  0.16    NA  1.38
3004    NA    NA  0.15    NA  1.36
3005  0.12  0.12  0.14    NA  1.23
3006  0.12  0.12  0.15    NA  1.27
3007  0.12  0.12  0.14    NA  1.24
3008    NA    NA    NA    NA    NA
3009    NA    NA    NA    NA    NA
3010  0.12  0.12  0.14    NA  1.29

I would like to count how many columns per row contain a value, or alternatively, how many columns per row contain <NA> (and then I can do the calculation myself, i.e. total rows - number of rows with <NA>).

So the output in the first case would be:

       Number
3000      4
3001      0
3002      0
3003      4
3004      2
3005      4
3006      4
3007      4
3008      0
3009      0
3010      4

I thought there might be a rowCount function but cannot find one.

And from my understanding, count() is for counting the number of types of rows within a given column.

Thanks.

eBopBob
  • 123
  • 10

1 Answers1

1

Here is a solution with dplyr

  df <- data.frame(xxx2 = c(0.12,NA),xxx3 = c(0.14,NA),xx5 = c(.17,NA),xxx6 = c(NA,NA),xxx7 = c(1.42,NA))
    df

df example
     xxx2 xxx3  xx5 xxx6 xxx7
    1 0.12 0.14 0.17   NA 1.42
    2   NA   NA   NA   NA   NA

Code:

library(dplyr)

df %>% rowwise() %>% mutate(count=sum(!is.na(c_across(everything()))))

Output:

  xxx2  xxx3   xx5 xxx6   xxx7 count
  <dbl> <dbl> <dbl> <lgl> <dbl> <int>
1  0.12  0.14  0.17 NA     1.42     4
2 NA    NA    NA    NA    NA        0
cgvoller
  • 873
  • 1
  • 14