0

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?

taylorpot
  • 25
  • 4
  • 1) In `for` loop you probably need `for (i in 1:nrow(Results2019))` 2) `Results2019$Cand1Pct > Results2019$Cand2Pct` should be `Results2019$Cand1Pct[i] > Results2019$Cand2Pct[i]` and same `else if` part. BTW use `ifelse` which is vectorized. – Ronak Shah Sep 24 '20 at 04:46
  • Accidentally mistyped the for loop part, thanks for that! How would I use ```ifelse``` here? Can that be nested in the for loop? – taylorpot Sep 24 '20 at 05:09
  • You don't need `for` loop : `Results2019$PrecinctWinner <- ifelse(Results2019$Cand1Pct > Results2019$Cand2Pct, 'Cand1', 'Cand2')` – Ronak Shah Sep 24 '20 at 05:24

0 Answers0