This is a small portion of the dataframe I am working with for reference.我正在使用R中的数据框(MG53_HanLab),其中包含一列Time,有几列名为" MG53"在其中,有几个名为" F2"和#34; Iono"在他们中。我想比较每个时间点每组的方法。我知道我必须对数据进行子集化并尝试过
control <- MG53_HanLab[c(2:11)]
F2 <- MG53_HanLab[c(12:23)]
iono <- MG53_HanLab[c(24:33)]
已创建3个新数据帧。
我的问题是:如何逐行比较两个数据帧,看看每个表的均值是否有差异?
答案 0 :(得分:2)
rowMeans
感觉更简单,就像@Chi Pak建议的那样。
#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)
#create data frame
df<-data.frame(time,A_1,A_2,B_1_1,B_1_2,B_2)
#subset column groups into individual data frames using regular expression
df.a<-df[,grep('A_',colnames(df))]
#calculate rowMeans
a.mean<-rowMeans(df.a)
#repeat for other column groups
df.b<-df[,grep('B_',colnames(df))]
b.mean<-rowMeans(df.b)
#recombine to view side by side
df.mean<-data.frame(a.mean,b.mean)
答案 1 :(得分:1)
您可以使用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")