您可以使用data.table
軟件包,其中有一些數據將列翻轉成行並返回。
#import library
library(data.table)
#create example data
time<-seq(1.0,6.0,.5)
A_1<-runif(11)
A_2<-runif(11)
B_1_1<-runif(11)
B_1_2<-runif(11)
B_2<-runif(11)
#instantiate data table from example data
dt <-data.table(time,A_1,A_2,B_1_1,B_1_2,B_2)
#flip all columns with underscores in name into rows using regular expression
dt.m = melt(dt,id.vars=c("time"), measure.vars=grep('_',colnames(dt)))
#remove characters after '_' to homogenize column groups
dt.m[,variable:=sub("_.*","",variable)]
#calculate the mean grouped by time and column groups
dt.mean<-dt.m[,lapply(.SD,mean),by=.(time,variable)]
#flip rows back to columns
dcast(dt.mean,time~variable,value.var = "value")
退房'rowMeans' – CPak