2

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

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 组合,或者如何创建一个新行然后将它们输入到主表中。

顺便说一句,如果这只是一种愚蠢的方式来处理我正在做的事情,请随时指出>)

4

2 回答 2

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)
于 2013-03-11T06:13:21.507 回答
3

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

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)
于 2013-03-11T06:56:51.023 回答