data<-read.table("Exp4 data.txt",header=T)
str(data)

data$cb<-as.factor(data$cb)
data$subject<-as.factor(data$subject)
data$code<-as.factor(data$code)
data$item<-as.factor(data$item)
data$trial<-as.factor(data$trial)
data$enh_pos<-as.factor(data$enh_pos)
str(data)


ifelse(grepl('b',data$cb),"b","a")->data$key

with(data, aggregate(acc=="cor",by=list(subject=subject),mean))->subacc
names(subacc)[2]<-"accuracy"

plot(subacc$accuracy)
hist(subacc$accuracy)


subacc$subject[subacc$accuracy<0.56]->under56

#high subject accuracy

subset(data,!subject%in%under56)->dh #data of high accuracy subjects only


with(subset(data,!subject%in%under56),xtabs(~cb))/256


round(with(subset(dh,trial_type=="same"),xtabs(acc=="cor"~target_type+enhancement)/xtabs(~target_type+enhancement))*100,1) #mean accuracy, same trials


round(with(subset(dh,trial_type=="different"),xtabs(acc=="cor"~target_type+enhancement+diff_alt)/xtabs(~target_type+enhancement+diff_alt))*100,1) #mean accuracy, different trials

round(with(subset(dh,trial_type=="different"),xtabs(acc=="cor"~target_type+diff_alt)/xtabs(~target_type+diff_alt))*100,1) #collapsed, different trials



library(lme4)

library(phia)

library(nloptr)
defaultControl <- list(algorithm="NLOPT_LN_BOBYQA",xtol_rel=1e-6,maxeval=1e5)
nloptwrap2 <- function(fn,par,lower,upper,control=list(),...) {
    for (n in names(defaultControl)) 
      if (is.null(control[[n]])) control[[n]] <- defaultControl[[n]]
    res <- nloptr(x0=par,eval_f=fn,lb=lower,ub=upper,opts=control,...)
    with(res,list(par=solution,
                  fval=objective,
                  feval=iterations,
                  conv=if (status>0) 0 else status,
                  message=message))
}			



#accuracy 

#same trials

subset(dh,trial_type=="same")->same


glmer(acc=="cor"~target_type*enhancement*key+(target_type*enhancement|subject)+(target_type*enhancement|item),data=same,family="binomial",
control=glmerControl(optimizer="bobyqa"))->same_fullExp #Converged

Anova(same_fullExp)


#different trials

subset(dh,trial_type=="different")->different


glmer(acc=="cor"~target_type*enhancement*diff_alt*Experiment+(target_type+diff_alt+enhancement|subject)+(target_type+diff_alt+enhancement|item),
data=different,family="binomial",control=glmerControl(optimizer="nloptwrap2"))->diff_Expmax #Converged

Anova(diff_Expmax)
testInteractions(diff_Expmax,pairwise=c("target_type"),fixed=c("diff_alt"),adjustment="none")



