Calculate row means on subset of columns
Calculate row means on a subset of columns:
Create a new data.frame which specifies the first column from DF as an column called ID and calculates the mean of all the other fields on that row, and puts that into column entitled '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
Starting with your data frame DF
, you could use the data.table
package:
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
You can create a new row with $
in your data frame corresponding to the Means
DF$Mean <- rowMeans(DF[,2:4])
Using dplyr:
library(dplyr)
# exclude ID column then get mean
DF %>%
transmute(ID,
Mean = rowMeans(select(., -ID)))
Or
# 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