计算列子集上的行均值

给定一个样本数据框:


C1<-c(3,2,4,4,5)

C2<-c(3,7,3,4,5)

C3<-c(5,4,3,6,3)

DF<-data.frame(ID=c("A","B","C","D","E"),C1=C1,C2=C2,C3=C3)


DF

    ID C1 C2 C3

  1  A  3  3  5

  2  B  2  7  4

  3  C  4  3  3

  4  D  4  4  6

  5  E  5  5  3

创建包含ID列和每一行均值的第二个数据框的最佳方法是什么?像这样:


ID  Mean

A    3.66

B    4.33

C    3.33

D    4.66

E    4.33

类似于:


RM<-rowMeans(DF[,2:4])

我想使方法与他们的方法保持一致ID。


aluckdog
浏览 453回答 3
3回答

湖上湖

计算列子集上的行均值:创建一个新的data.frame,它将DF中的第一列指定为ID列,并计算该行上所有其他字段的均值,并将其放入名为“ Means”的列中:data.frame(ID=DF[,1], Means=rowMeans(DF[,-1]))&nbsp; ID&nbsp; &nbsp; Means1&nbsp; A 3.6666672&nbsp; B 4.3333333&nbsp; C 3.3333334&nbsp; D 4.6666675&nbsp; E 4.333333

LEATH

从数据框开始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.framesetDT(DF)# EDIT: To get the column name 'Mean':DF[, .(Mean = rowMeans(.SD)), by = ID]#&nbsp; &nbsp; &nbsp; ID&nbsp; &nbsp; &nbsp;Mean# [1,]&nbsp; A 3.666667# [2,]&nbsp; B 4.333333# [3,]&nbsp; C 3.333333# [4,]&nbsp; D 4.666667# [5,]&nbsp; E 4.333333

幕布斯6054654

使用dplyr:library(dplyr)# exclude ID column then get meanDF %>%&nbsp; transmute(ID,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Mean = rowMeans(select(., -ID)))要么# select the columns to include in meanDF %>%&nbsp; transmute(ID,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Mean = rowMeans(select(., C1:C3)))#&nbsp; &nbsp;ID&nbsp; &nbsp; &nbsp;Mean# 1&nbsp; A 3.666667# 2&nbsp; B 4.333333# 3&nbsp; C 3.333333# 4&nbsp; D 4.666667# 5&nbsp; E 4.333333
打开App,查看更多内容
随时随地看视频慕课网APP