How to use ddply with a custom function and return the original data frame along with the result

Take a look at my data from a task with many tests, each of which consists of 5 questions (the following code will generate a representative subset):

Subject<-c(rep(400,20),rep(401,20))
RT<-sample(x=seq(250:850),size=40)
accuracy<-c(1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 
1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0)
trial<-rep(rep(1:4, each=5),2)
question<-rep(seq(from=0,to=4),8)
data<-data.frame(Subject,trial,question,RT,accuracy)
remove(Subject,RT,accuracy,trial,question)

and will look something like this:

      ID    trial  question   RT   accuracy
1     400   1      0          131  1
2     400   1      1          768  1
3     400   1      2          300  1
4     400   1      3          130  1
5     400   1      4          168  1
...
36    401   1      0          273  1
37    401   1      1          803  1
38    401   1      2          786  0
39    401   1      3          712  1
40    401   1      4          254  0

. , , ( = 1). 400 c (1,1,1,1,1), , . 401 c (0,0,0,0,0), , . , , Plyr , :

: 1) , 2) 2) , 1, 0

, :

allOK<-function(x) {
  c<-length(x[,1]) #get number of questions for this trial
  s<-sum(x$accuracy) #get sum of accuracies
  return ( data.frame(rep(as.integer(s==c))) ) #return allOK vector
}

:

alloktest<-ddply(.data=data,c("Subject","trial"), .fun=allOK, .progress = "text")

, , alloktest Subject, trial . , , , (, aok).

? , :

      ID    trial  question   RT   accuracy  aok
1     400   1      0          131  1          1
2     400   1      1          768  1          1
3     400   1      2          300  1          1
4     400   1      3          130  1          1
5     400   1      4          168  1          1
...
36    401   1      0          273  1          0
37    401   1      1          803  1          0
38    401   1      2          786  0          0
39    401   1      3          712  1          0
40    401   1      4          254  0          0

!

+5
1

, , - mutate, plyr transform

 alloktest<-ddply(.data=data,c("Subject","trial"), mutate,  
     aok = sum(accuracy) == length(accuracy))

, .

+4

All Articles