Skip to contents

Calculates the sum of each row (column) in a data.frame object, with options for handling NA values, preserving row names, and appending results to the original data.frame.

Only numeric columns are considered for calculations.

Usage

colSums3(
  x,
  na.rm = FALSE,
  useNames = FALSE,
  silence_warnings = FALSE,
  no_check = FALSE
)

rowSums3(
  x,
  na.rm = FALSE,
  useNames = FALSE,
  silence_warnings = FALSE,
  no_check = FALSE,
  append = FALSE
)

Arguments

x

A data.frame with at least one row and one column.

na.rm

Logical. Should NA values be removed before calculation? Default is FALSE.

useNames

Logical. Should the resulting vector preserve row (column) names from the input data.frame? Default is FALSE.

silence_warnings

Logical. Should warnings be suppressed when non-numeric columns are dropped? Default is FALSE.

no_check

Logical. Skip input validation and numeric column filtering? Default is FALSE.

append

Logical. Should the sums be appended as a new column row_sums instead of returning them as a vector? Default is FALSE.

Value

If append = FALSE (default), returns a numeric vector of row (column) sums. If useNames = TRUE and the input has non-default row (column) names, the returned vector will preserve these names.

If append = TRUE, returns the original data.frame with an additional row_sums column.

See also

colSums3 for column-wise summation

Author

Yinchun Su

Examples

# example code
df <- data.frame(
  a = 1:5,
  b = 6:10,
  c = 11:15
)

# Basic usage
rowSums3(df)
#> [1] 18 21 24 27 30
colSums3(df)
#> [1] 15 40 65

# Append sums as new column
rowSums3(df, append = TRUE)
#>   a  b  c row_sums
#> 1 1  6 11       18
#> 2 2  7 12       21
#> 3 3  8 13       24
#> 4 4  9 14       27
#> 5 5 10 15       30

# Preserve row names
rownames(df) <- paste0("row", seq_len(nrow(df)))
colnames(df) <- LETTERS[seq_len(ncol(df))]
rowSums3(df, useNames = TRUE)
#> row1 row2 row3 row4 row5 
#>   18   21   24   27   30 
colSums3(df, useNames = TRUE)
#>  A  B  C 
#> 15 40 65