3 回答
TA贡献2003条经验 获得超2个赞
计算列子集上的行均值:
创建一个新的data.frame,它将DF中的第一列指定为ID列,并计算该行上所有其他字段的均值,并将其放入名为“ Means”的列中:
data.frame(ID=DF[,1], Means=rowMeans(DF[,-1]))
ID Means
1 A 3.666667
2 B 4.333333
3 C 3.333333
4 D 4.666667
5 E 4.333333
TA贡献1936条经验 获得超6个赞
从数据框开始DF,您可以使用以下data.table包:
library(data.table)
## EDIT: As suggested by @MichaelChirico, setDT converts a
## data.frame to a data.table by reference and is preferred
## if you don't mind losing the data.frame
setDT(DF)
# EDIT: To get the column name 'Mean':
DF[, .(Mean = rowMeans(.SD)), by = ID]
# ID Mean
# [1,] A 3.666667
# [2,] B 4.333333
# [3,] C 3.333333
# [4,] D 4.666667
# [5,] E 4.333333
TA贡献1876条经验 获得超7个赞
使用dplyr:
library(dplyr)
# exclude ID column then get mean
DF %>%
transmute(ID,
Mean = rowMeans(select(., -ID)))
要么
# select the columns to include in mean
DF %>%
transmute(ID,
Mean = rowMeans(select(., C1:C3)))
# ID Mean
# 1 A 3.666667
# 2 B 4.333333
# 3 C 3.333333
# 4 D 4.666667
# 5 E 4.333333
- 3 回答
- 0 关注
- 459 浏览
添加回答
举报