简体   繁体   中英

Analysis over time comparing 2 dataframes row by row

This is a small portion of the dataframe I am working with for reference. I am working with a data frame (MG53_HanLab) in R that has a column for Time, several columns with the name "MG53" in them, several columns with the name "F2" and several with "Iono" in them. I would like to compare the means of each group for each time point. I understand that I have to subset the data and have tried doing

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

which has created 3 new dataframes.

My question is: How do I compare two dataframes row by row to see if there is a difference in the means for each table?

rowMeans feels simpler as @Chi Pak suggested.

#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)

You can use the data.table package with some data flipping columns to rows and back again.

#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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM