I have a data frame with two columns showing the percentage of the vote two candidates won in an election in about 40 precincts. I want to make a third column displaying the name of the candidate that won each precinct. I wrote a for loop and in it nested an if loop to compare the two columns in each row of the data frame and print the winner's name in the third column. However, R keeps spitting out "the condition has length > 1 and only the first element will be used" and printing the same name in each row of the third column.
Here's the loop:
for (i in nrow(Results2019)) {
oneprecinct <- Results2019[i,]
if (Results2019$Cand1Pct > Results2019$Cand2Pct) {
Results2019$PrecinctWinner <- "Cand1"
} else if (Results2019$Cand2Pct > Results2019$Cand1Pct) {
Results2019$PrecinctWinner <- "Cand2"
}
Results2019[i,] <- oneprecinct
}
To clarify, each row in the PrecinctWinner column reads Cand1. If it makes a difference, I created the PrecinctWinner column for the first time in the loop. Any suggestions?