-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy path1. Find winner
101 lines (67 loc) · 2.57 KB
/
1. Find winner
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
competitionGT=function(players, path, download=TRUE){
#Set errortest default value
errortest=NA
#Initialize file count
k=1
#Create file references
maxFiles=2000
filenames=vector()
filenames[1]=paste(path, "/report.csv", sep="")
for(i in 1:maxFiles) filenames[i+1]=paste(path, "/report(", i, ").csv", sep="")
scoreBoard=as.data.frame(matrix(NA, 0, 3))
colnames(scoreBoard)=c("Round", "Player", "Score")
#Set initial value for round winner
roundWinner=as.character(players[1,1])
#####START THE COMPETITION
start=2
if(download==TRUE) {stop=nrow(players)
} else {stop=length(list.files(path))}
for(i in seq(start, stop, by=4)){
#roundWinner always participates in the competition
query=roundWinner
#Select batch of four players to go up against the roundWinner. The min function ensures that there are no empty slots
batch=players[i:min((i+3),nrow(players)),1]
#If the files haven't been downloaded already, create Google Trends query, download and import file
if(download==TRUE){
#File selector k
k=length(list.files(path))+1
for(j in 1:length(batch)) query=paste(query, "%2C ", batch[j], sep="")
URL=paste("http://www.google.com/trends/trendsReport?hl=en-US&q=", query,"&cmpt=q&content=1&export=1", sep="")
browseURL(URL)
Sys.sleep(4)
#Error handler. Try do read file. If it fails, wait 8 seconds. If it fails again, wait 8 seconds more.
errortest=tryCatch(
read.csv(filenames[k], header=FALSE, blank.lines.skip=FALSE, stringsAsFactors=FALSE),
error=function(e) e
)
if(inherits(errortest, "error")){
Sys.sleep(8)
}
errortest=tryCatch(
read.csv(filenames[k], header=FALSE, blank.lines.skip=FALSE, stringsAsFactors=FALSE),
error=function(e) e
)
if(inherits(errortest, "error")){
Sys.sleep(8)
}
}
#Make sure that the files can be loaded. If not, skip this iteration
if(!inherits(errortest, "error")){
players.raw=read.csv(filenames[k], header=FALSE, blank.lines.skip=FALSE, stringsAsFactors=FALSE)
#Initialize results
results=data.frame(matrix(NA, (nrow=length(players.raw)-1), ncol=3))
results[,1]=k
for(i in 1:(ncol(players.raw)-1)) results[i,2]=players.raw[5,i+1]
for(i in 1:(ncol(players.raw)-1)) results[i,3]=as.numeric(as.character(players.raw[(which(players.raw=="")[2]-2),i+1]))
highScore=max(results[,3])
colnames(results)=c("Round", "Player", "Score")
roundWinner=results[which(results[,3]==highScore),2]
scoreBoard=rbind(scoreBoard, results)
k=k+1 #Move file selector one step forward
winner=data.frame("Winner", roundWinner, highScore)
colnames(winner)=c("Round", "Player", "Score")
scoreBoard=rbind(scoreBoard, winner)
}
}
return(scoreBoard)
}