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

これが私が思いついたすべてです。テーブル内のどのセルがどのConditionxReqresponseコンボに属しているのか、または新しい行を作成してマスターテーブルにフィードする方法がわかりません。

ちなみに、これが私がやっていることにアプローチするためのばかげた方法であるなら、それを自由に指摘してください>)

4

2 に答える 2

3

@Hemmoの答えは、オブジェクトを順番に成長させることです。ファイルの量が多い場合、これは非常に遅くなる可能性があります。よりRスタイルのアプローチは、forループを使用するのではなく、最初にファイルのベクトルを作成し、次に適用スタイルループを使用してそれらをループすることです。plyrライブを少し簡単にするため、パッケージの適用ループを使用します。

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 に答える
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 に答える