Calculate row (column) sums for R data.frame object
Source: R/colMeans3.R, R/rowMeans3.R
rowMeans3.RdCalculates the mean 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
colMeans3(
x,
na.rm = FALSE,
useNames = FALSE,
silence_warnings = FALSE,
no_check = FALSE
)
rowMeans3(
x,
na.rm = FALSE,
useNames = FALSE,
silence_warnings = FALSE,
no_check = FALSE,
append = FALSE
)Arguments
- x
A
data.framewith 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 isFALSE.- 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 means be appended as a new column
row_meansinstead of returning them as a vector? Default isFALSE.
Value
If append = FALSE (default), returns a numeric vector of row (column)
means. 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_means column.
Examples
df <- data.frame(
a = 1:5,
b = 6:10,
c = 11:15
)
# Basic usage
rowMeans3(df)
#> [1] 6 7 8 9 10
colMeans3(df)
#> [1] 5.00000 13.33333 21.66667
# Append means as new column
rowMeans3(df, append = TRUE)
#> a b c row_means
#> 1 1 6 11 6
#> 2 2 7 12 7
#> 3 3 8 13 8
#> 4 4 9 14 9
#> 5 5 10 15 10
# Preserve row names
rownames(df) <- paste0("row", seq_len(nrow(df)))
colnames(df) <- LETTERS[seq_len(ncol(df))]
rowMeans3(df, useNames = TRUE)
#> row1 row2 row3 row4 row5
#> 6 7 8 9 10
colMeans3(df, useNames = TRUE)
#> A B C
#> 5.00000 13.33333 21.66667