Skip to contents

Count or Sum Up Values Within Groups of rows

Usage

countOrSum(x, by = NULL, sum.up = NULL)

Arguments

x

data frame

by

vector of names of columns in x to be grouped by

sum.up

name of column in x containing numeric values to be summed up. If NULL (default) rows within groups are counted instead of summing up values within each group

Value

object of class xtabs with as many dimensions as there are values in by

Examples

# Create a data frame with example data
x <- data.frame(
  Group = rep(c("A", "B", "C"), 4),
  Even = rep(c(FALSE, TRUE), 6),
  Value = seq_len(12)
)

# Count the number of rows for each group
countOrSum(x, "Group")
#> Group
#> A B C 
#> 4 4 4 
countOrSum(x, c("Group", "Even"))
#>      Even
#> Group FALSE TRUE
#>     A     2    2
#>     B     2    2
#>     C     2    2

# Sum up the values in column "Value" for each group
countOrSum(x, "Group", sum.up = "Value")
#> Group
#>  A  B  C 
#> 22 26 30 
countOrSum(x, c("Group", "Even"), sum.up = "Value")
#>      Even
#> Group FALSE TRUE
#>     A     8   14
#>     B    16   10
#>     C    12   18