# lab2_RawData.R
# 13 September 2010
# command file for reading in the PsyScope data file to tabulate
# the response frequencies for use in RscorePlus.
# The PsyScope file should have been edited to replace the column
# header "Condition" with "Gender Target Eyes"
# The response table is printed and a text output
# file is written that can be used by RscorePlus as input

# put your name here. It will be used to create the output file
myName <- "Joe Blow"

fn <- file.choose()
df <- read.table(fn, header = TRUE, skip = 15, nrows = 64+128)

# make data frame with just the rating trials data
df.rec <- df[ 65:192, ]

# remove the [N/A] level from the key column
levels(df.rec$keys) <- c("[1]", "[2]", "[3]", "[4]", "[5]", "[6]", NA)

# add new column called "Signal" for the SDT analysis
df.rec <- cbind(df.rec, Signal = df.rec$Eyes)

# add a new level to the factor "Signal" and call it "New"
df.rec[, "Signal"] <- factor(df.rec[, "Signal"], levels=c("New","NoEyes","Eyes"))

# set all the new face signal trials to "New"
df.rec[df.rec$Target=="new", "Signal"] <- "New"

# compute frequency contingency table and print it
t <- with(df.rec, table(Signal, keys))
print(t)

# write out a text file for RscorePlus input
tab <- "\t"		# tab character
eol <- "\r"		# Mac end-of-line character
# open the output file
outputFileName <- paste(myName,".txt", sep = "")
of <- file(outputFileName, open = "wt")
# write the first line to file
cat("Heading", eol, sep = "", file = of) 
# create text lines for output file
l1 <- paste(myName, eol, sep = "")
l2 <- paste("6",tab,"3",tab,"1",tab,"0",tab,"0",tab,"1",tab,"SINT",eol,sep="")
l3 <- paste("labels",tab,"R_1",tab,"R_2",tab,"R_3",tab,"R_4",tab,"R_5",tab,"R_6",eol,sep="")
l4 <- paste("new",   tab,t[1,1],tab,t[1,2],tab,t[1,3],tab,t[1,4],tab,t[1,5],tab,t[1,6],eol,sep="")
l5 <- paste("oldNoE",tab,t[2,1],tab,t[2,2],tab,t[2,3],tab,t[2,4],tab,t[2,5],tab,t[2,6],eol,sep="")
l6 <- paste("oldEye",tab,t[3,1],tab,t[3,2],tab,t[3,3],tab,t[3,4],tab,t[3,5],tab,t[3,6],eol,sep="")
l7 <- paste("0.0",tab,"1.0",tab,"0.5",tab,"1.0",tab,"1.0",tab,"1.0",eol,sep="")
l8 <- paste("0",tab,"0",tab,"1",tab,"1",tab,"1",tab,"1",eol,sep="")
# write lines to the output file	
cat(l1, sep = "", file = of)
cat(l2, sep = "", file = of)
cat(l3, sep = "", file = of)
cat(l4, sep = "", file = of)
cat(l5, sep = "", file = of)
cat(l6, sep = "", file = of)
cat(l7, sep = "", file = of)
cat(l8, sep = "", file = of)
# write lines at the end of the file
cat("end of file", eol, sep = "", file = of)
cat("-1", eol, sep = "", file = of)
close(of)
print(paste("The frequencies have been written to file", outputFileName))
print("Use it as input to RscorePlus")