R编程中计算对象每一行的平均值——rowMeans()函数
R 语言中的rowMeans()函数用于找出数据框、矩阵或数组的每一行的平均值。
Syntax: rowMeans(data)
Parameter:
data: data frame, array, or matrix
示例 1
# R program to illustrate
# rowMean function
# Create example values
# Set seed
set.seed(1234)
# Create example data
data <- data.frame(matrix(round(runif(12, 2, 20)),
nrow = 4, ncol = 3))
# Print data
print(rowMeans(data))
输出:
[1] 11.666667 12.666667 9.666667 10.333333
示例 2:
# R program to illustrate
# rowMean function
# Create example data with NA
data_na <- data.frame(matrix(round(runif(12, 2, 20)),
nrow = 4, ncol = 3))
data_na[rbinom(length(data_na), 1, 0.3) == 1] <- NA
data_na <- as.data.frame(data_na)
print(rowMeans(data_na, na.rm = TRUE))
输出:
[1] 3 16 9 3