library("ggplot2") #plotting
library("plyr") # to split and work with dataframes
library("Hmisc") # to use the function mean_cl_boot
data<-read.table("datLopezMoliner.txt",header=TRUE)
data$speed<-as.factor(data$speed)
x.limits<-c(min(data$phase),max(data$phase))
split.variables<-c("subject","cond","speed")
psy.fit<-function(df) { # funtion to fit cumulative gaussians
guess<-c(0.5,0.5) # guess mean and slope
gaussian.op<-function(p,x,y){ ypred<- pnorm(x,p[1],p[2]); sum((y-ypred)^2) }
results<-ddply(df,.(phase),numcolwise(mean))
model<-optim(guess,gaussian.op,x=results$phase,y=results$response)$par
data.frame(mean=model[1],sd=model[2])
}
psy.fits<-ddply(data,split.variables,psy.fit) # plyr (fitting by split variable)
psychometric<-function(df) {
grid <- data.frame(phase = seq(x.limits[1],x.limits[2], length = 200))
grid$response <- pnorm(grid$phase,mean=df$mean,sd=df$sd)
grid
}
psychometrics<-ddply(psy.fits,split.variables,psychometric)
theme_set(theme_bw()) # plotting; the error bars are bootstrapping conf int
p<-ggplot(data, aes(x=phase, y=response, colour=cond)) + facet_grid(speed~subject)
p<-p+stat_summary(fun.data = "mean_cl_boot",position=position_jitter(width=0.04)) #avoid overplotting
p<-p+geom_line(data=psychometrics) # plot the psychometric functions
p