0

How can I count non-NA values per row including columns from "b" to "c"?

library(tidyverse)

d = tibble(a = c("Tom", "Mary", "Ben", "Jane", "Lucas", "Mark"),
           b = c(NA, 3, 6, NA, 5, NA),
           c = c(2, NA, 6, 7, 1, 9))

d

enter image description here

Output should have an extra column with values as follows: 1, 1, 2, 1, 2, 1

Tidyverse solutions are especially appreciated!

user438383
  • 5,716
  • 8
  • 28
  • 43
st4co4
  • 445
  • 3
  • 10

2 Answers2

2

A possible solution:

library(dplyr)

d %>% 
  mutate(result = rowSums(!is.na(across(b:c))))

#> # A tibble: 6 × 4
#>   a         b     c result
#>   <chr> <dbl> <dbl>  <dbl>
#> 1 Tom      NA     2      1
#> 2 Mary      3    NA      1
#> 3 Ben       6     6      2
#> 4 Jane     NA     7      1
#> 5 Lucas     5     1      2
#> 6 Mark     NA     9      1
PaulS
  • 21,159
  • 2
  • 9
  • 26
0

Using select instead of across:

library(tidyverse)
d = tibble(a = c("Tom", "Mary", "Ben", "Jane", "Lucas", "Mark"),
           b = c(NA, 3, 6, NA, 5, NA),
           c = c(2, NA, 6, 7, 1, 9))

d %>%
  mutate(output = rowSums(!is.na(select(., -a))))
#> # A tibble: 6 × 4
#>   a         b     c output
#>   <chr> <dbl> <dbl>  <dbl>
#> 1 Tom      NA     2      1
#> 2 Mary      3    NA      1
#> 3 Ben       6     6      2
#> 4 Jane     NA     7      1
#> 5 Lucas     5     1      2
#> 6 Mark     NA     9      1

Created on 2022-07-15 by the reprex package (v2.0.1)

base R option:

library(tidyverse)
d = tibble(a = c("Tom", "Mary", "Ben", "Jane", "Lucas", "Mark"),
           b = c(NA, 3, 6, NA, 5, NA),
           c = c(2, NA, 6, 7, 1, 9))

d$output <- apply(d[2:3], 1, function(x) sum(!is.na(x)))
d
#> # A tibble: 6 × 4
#>   a         b     c output
#>   <chr> <dbl> <dbl>  <int>
#> 1 Tom      NA     2      1
#> 2 Mary      3    NA      1
#> 3 Ben       6     6      2
#> 4 Jane     NA     7      1
#> 5 Lucas     5     1      2
#> 6 Mark     NA     9      1

Created on 2022-07-15 by the reprex package (v2.0.1)

Quinten
  • 35,235
  • 5
  • 20
  • 53