row_count() mimics base R's rowSums(), with sums for a specific value indicated by count. Hence, it is equivalent to rowSums(x == count, na.rm = TRUE). However, this function is designed to work nicely within a pipe-workflow and allows select-helpers for selecting variables and the return value is always a data frame (with one variable).

col_count() does the same for columns. The return value is a data frame with one row (the column counts) and the same number of columns as x.

row_count(x, ..., count, var = "rowcount", append = TRUE)

col_count(x, ..., count, var = "colcount", append = TRUE)

Arguments

x

A vector or data frame.

...

Optional, unquoted names of variables that should be selected for further processing. Required, if x is a data frame (and no vector) and only selected variables from x should be processed. You may also use functions like : or tidyselect's select-helpers. See 'Examples' or package-vignette.

count

The value for which the row or column sum should be computed. May be a numeric value, a character string (for factors or character vectors), NA, Inf or NULL to count missing or infinite values, or null-values.

var

Name of new the variable with the row or column counts.

append

Logical, if TRUE (the default) and x is a data frame, x including the new variables as additional columns is returned; if FALSE, only the new variables are returned.

Value

For row_count(), a data frame with one variable: the sum of count appearing in each row of x; for col_count(), a data frame with one row and the same number of variables as in x: each variable holds the sum of count appearing in each variable of x. If append = TRUE, x including this variable will be returned.

Examples

dat <- data.frame(
  c1 = c(1, 2, 3, 1, 3, NA),
  c2 = c(3, 2, 1, 2, NA, 3),
  c3 = c(1, 1, 2, 1, 3, NA),
  c4 = c(1, 1, 3, 2, 1, 2)
)

row_count(dat, count = 1, append = FALSE)
#>   rowcount
#> 1        3
#> 2        2
#> 3        1
#> 4        2
#> 5        1
#> 6        0
row_count(dat, count = NA, append = FALSE)
#>   rowcount
#> 1        0
#> 2        0
#> 3        0
#> 4        0
#> 5        1
#> 6        2
row_count(dat, c1:c3, count = 2, append = TRUE)
#>   c1 c2 c3 c4 rowcount
#> 1  1  3  1  1        0
#> 2  2  2  1  1        2
#> 3  3  1  2  3        1
#> 4  1  2  1  2        1
#> 5  3 NA  3  1        0
#> 6 NA  3 NA  2        0

col_count(dat, count = 1, append = FALSE)
#> # A tibble: 1 × 4
#>      c1    c2    c3    c4
#>   <int> <int> <int> <int>
#> 1     2     1     3     3
col_count(dat, count = NA, append = FALSE)
#> # A tibble: 1 × 4
#>      c1    c2    c3    c4
#>   <int> <int> <int> <int>
#> 1     1     1     1     0
col_count(dat, c1:c3, count = 2, append = TRUE)
#>   c1 c2 c3 c4
#> 1  1  3  1  1
#> 2  2  2  1  1
#> 3  3  1  2  3
#> 4  1  2  1  2
#> 5  3 NA  3  1
#> 6 NA  3 NA  2
#> 7  1  2  1 NA