【问题标题】:Analysis over time comparing 2 dataframes row by row随着时间的推移分析逐行比较 2 个数据帧
【发布时间】:2017-12-22 07:41:50
【问题描述】:

This is a small portion of the dataframe I am working with for reference.我正在使用 R 中的一个数据框 (MG53_HanLab),它有一个时间列,其中有几个名为“MG53”的列,几个名为“F2”的列和几个名为“Iono”的列在他们之中。我想比较每个时间点每个组的平均值。我知道我必须对数据进行子集化并尝试过

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

创建了 3 个新的数据框。

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

【问题讨论】:

  • 查看rowMeans

标签: r dataframe subset temporal-difference


【解决方案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")

【讨论】:

  • 当我继续分析数据时,此解决方案也可能对我有所帮助。也感谢您提供此解决方案!
【解决方案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)

【讨论】:

  • 尽量不要发布多个答案。您可以将其添加到原始答案中。
  • @Sotos 我会,但这个meta question 暗示不同的方法需要不同的答案。我应该合并吗?
  • 好吧,我可能错了,但我一直认为字符有限制,因此可以选择添加多个答案
  • 谢谢!我不确定如何使用 grep 来调用我想要的列,因为我知道 grep 会导致 True False 输出。
猜你喜欢
  • 2017-01-20
  • 2014-04-09
  • 2019-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-10
  • 1970-01-01
  • 2018-07-27
相关资源
最近更新 更多