2017-07-17 76 views
3

This is a small portion of the dataframe I am working with for reference.我正在使用R中的一个数据帧(MG53_HanLab),它有一列Time,其中有多个名称为“MG53”的列,名为“F2 “和几个与”Iono“在他们。我想比较每个时间点的每个组的手段。我知道我必须对数据进行子集化并尝试做按时间比较分析2个数据帧的分析

control <- MG53_HanLab[c(2:11)] 
F2 <- MG53_HanLab[c(12:23)] 
iono <- MG53_HanLab[c(24:33)] 

已创建3个新的数据框。

我的问题是:如何逐行比较两个数据帧以查看每个表的平均值是否存在差异?

+1

退房'rowMeans' – CPak

回答

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) 
+0

尽量不要发布多个答案。您可以将其添加到您的原始答案中。 – Sotos

+0

@Sotos我会有,但这[元问题](https://meta.stackoverflow.com/questions/251070/are-multiple-answers-by-the-same-user-acceptable)意味着不同的方法保证不同的答案。我应该结合? – alaybourn

+0

嗯,我可能是错的,但我一直认为有字符的限制,因此选择添加多个答案 – Sotos

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") 
+0

此解决方案也可以帮助我,因为我继续分析数据。感谢您提供此解决方案! – Kristyn