2017-07-17 46 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