我正在尝试在我的data.frame中添加一行来吐出列的平均值。
这是我的数据框:
Weight Response
1 Control 59 0.0
2 Treatment 90 0.8
3 Treatment 47 0.1
4 Treamment 106 0.1
5 Control 85 0.7
6 Treatment 73 0.6
7 Control 61 0.2
我希望它成为:
Weight Response
1 Control 59 0.0
2 Treatment 90 0.8
3 Treatment 47 0.1
4 Treamment 106 0.1
5 Control 85 0.7
6 Treatment 73 0.6
7 Control 61 0.2
8 AVERAGES 74 0.3
谢谢!
答案 0 :(得分:7)
简单的一个:
rbind(data, AVERAGES=colMeans(data))
[编辑]如果您的data.frame
包含除numeric
之外的其他类型(例如factor
或character
),那么您可以使用更复杂但更安全的方法:
rbind(data, AVERAGES=as.data.frame(lapply(data, mean)))
简单示例:
data <- data.frame(
x_Date = Sys.Date()+1:3,
x_numeric = 1:3+.1,
x_POSIXt = Sys.time()+1:3,
x_factor = factor(letters[1:3]),
x_character = letters[1:3],
x_logical = c(TRUE,FALSE,TRUE),
x_complex = 1i+1:3,
stringsAsFactors = FALSE,
row.names=paste("Row",1:3)
)
rbind(data, AVERAGES=as.data.frame(lapply(data , mean)))
# Warning in mean.default(X[[4L]], ...) :
# argument is not numeric or logical: returning NA
# Calls: rbind -> as.data.frame -> lapply -> FUN -> mean.default
# Warning in mean.default(X[[5L]], ...) :
# argument is not numeric or logical: returning NA
# Calls: rbind -> as.data.frame -> lapply -> FUN -> mean.default
# x_Date x_numeric x_POSIXt x_factor x_character x_logical x_complex
# Row 1 2010-04-21 1.1 2010-04-20 23:30:42 a a 1.000000 1+1i
# Row 2 2010-04-22 2.1 2010-04-20 23:30:43 b b 0.000000 2+1i
# Row 3 2010-04-23 3.1 2010-04-20 23:30:44 c c 1.000000 3+1i
# AVERAGES 2010-04-22 2.1 2010-04-20 23:30:43 <NA> <NA> 0.666667 2+1i
logical
列转换为数字,而非数字列则转换为NA