如何制表多个数据文件的方法

时间:2013-03-11 05:58:16

标签: r plyr

我有多个格式如下的数据文件:

Condition    Score  Reqresponse 
   Z          1         b   
   Y          0         a   

我想读取多个数据文件,获得每个条件/ reqresponse组合的平均分数,然后将其表格列入主表格。我希望每个数据文件的每个方法都填充主表(或列表,无论如何)中的一行。

这是我尝试的内容

#loop reads data from source example with only 2 files named 1 and 2
for(i in 1:2)
{
n= paste(i,".txt", sep="")
data <- read.table(toString(n), header = TRUE, sep = "\t")

到目前为止这么好吗?在此之后,我迷路了。

Score <- ave(x = data$Score, data$Condition, data$Reqresponse, FUN = mean)
table(Score)
}

这就是我想出来的。我不知道表中的哪些单元属于哪个Condition x Reqresponse组合,或者如何创建新行然后将它们提供给主表。

顺便说一句,如果这只是一种愚蠢的方式来接近我正在做的事情,请随意指出&gt;)

2 个答案:

答案 0 :(得分:3)

这应该可行,虽然它可以进行相当多的优化:

all_data<-data.frame() #make empty data.frame (we don't know the size)
for(i in 1:2){ #go through all files    
  #add rows to the data frame
  all_data <- rbind(all_data,read.table(paste(i,".txt", sep=""), 
              header = TRUE, sep = "\t"))
}
#use tapply to compute mean
Score<-tapply(all_data$Score,list(all_data$Condition,all_data$Reqresponse),mean)
编辑:通过不完全使用主数据框可以实现更好的性能解决方案(尽管我不确定xtabs与tapply的效率):

#read the first file
data <- read.table(paste(1,".txt", sep=""),header = TRUE, sep = "\t"))
#number of 1's, formula is a equal to Score==1~Condition+Reqresponse
score1<-xtabs(xtabs(Score~.,data=data) 
#number of 0's, formula is a equal to Score==0~Condition+Reqresponse
score0<-xtabs(!Score~.,data=data)
for(i in 2:n){ #go through the rest of the files  

  data <- read.table(paste(i,".txt", sep=""),header = TRUE, sep = "\t"))

  #sum the number of combinations in file i.txt to previous values
  score1<-score1+xtabs(xtabs(Score~.,data=data) 
  score0<-score0+xtabs(!Score~.,data=data)  
}
#Compute the means   
Score<-score1/(score0+score1)

答案 1 :(得分:3)

@Hemmo的答案涉及按顺序增长一个对象。如果文件数量很大,这可能会变得非常慢。更R风格的方法不是使用for循环,而是首先创建文件向量,然后使用apply样式循环遍历它们。我将使用来自plyr pacakge的应用循环,因为这样可以让生活更轻松一些:

library(plyr)
file_list = sprintf("%s.txt", 1:2)
all_data = ldply(file_list, read.table, header = TRUE, sep = "\t")

之后,您可以使用另一个plyr函数来处理数据:

ddply(all_data, .(Condition, Reqresponse), summarise, mn = mean(Score))

您还可以使用基本R函数:

all_data = do.call("rbind", lapply(file_list, read.table, header = TRUE, sep = "\t"))
# Here I copy the tapply call of @Hemmo
Score<-tapply(all_data$Score,list(all_data$Condition,all_data$Reqresponse),mean)