Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 逐行比较2个数据帧的时间分析_R_Dataframe_Subset_Temporal Difference - Fatal编程技术网

R 逐行比较2个数据帧的时间分析

R 逐行比较2个数据帧的时间分析,r,dataframe,subset,temporal-difference,R,Dataframe,Subset,Temporal Difference,我正在使用R中的一个数据帧(MG53_HanLab),其中有一列表示时间,几列中有名称“MG53”,几列中有名称“F2”,还有几列中有“Iono”。我想比较每个时间点每组的平均值。我知道我必须对数据进行子集划分,并且已经尝试过这样做 control <- MG53_HanLab[c(2:11)] F2 <- MG53_HanLab[c(12:23)] iono <- MG53_HanLab[c(24:33)] control您可以使用带有一些数据的data.table包,将列

我正在使用R中的一个数据帧(MG53_HanLab),其中有一列表示时间,几列中有名称“MG53”,几列中有名称“F2”,还有几列中有“Iono”。我想比较每个时间点每组的平均值。我知道我必须对数据进行子集划分,并且已经尝试过这样做

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

control您可以使用带有一些数据的
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
感觉像@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)
#创建示例数据

timeCheck out
rowMeans
尽量不要发布多个答案。您可以将其添加到原始答案中。@Sotos我会有,但这意味着不同的方法需要不同的答案。我应该合并吗?我可能错了,但我一直认为字符是有限的,因此可以选择添加多个答案谢谢!我不确定如何使用grep调用我想要的列,因为我知道grep会导致真-假输出。这个解决方案也可以帮助我继续分析数据。也感谢您提供此解决方案!