Home > OS >  Populate vectors with 2 for loops
Populate vectors with 2 for loops

Time:06-03

I may be misunderstanding how for loops work, but I'm having hard time comprehending why the current code doesn't populate vectors (the vectors evidently remain NA, although the code itself runs). I imagine there may also be a way to subset all of this information using ifelse(), but I'm experiencing "coder's block".

Issue (elaborated): I am trying to code a running Electoral College projection based on a betting market from the 2008 presidential cycle, over the final 90 days until Election Day. I justify using two for loops because the code needs to check conditional statements on a particular day and add a particular value to a preexisting sum at on that day. In other words, if the betting price for Obama is higher than McCain on a particular for a particular state that state's electoral votes are awarded to Obama on that day, and visa versa. Again, the code runs, but the vectors apparently remain NA.

Key of Relevant Variables

EV, electoral votes of that particular state
X, a unique value assigned to each observation
day, date class PriceD, betting price for the Dem candidate PriceR, betting price for the Rep candidate DaysToEday, a numeric value indicating the difference between variable day and election day (2008-11-04)

Code in Question

Obama08.ECvotesByDay <- McCain08.ECvotesByDay <- rep(NA, 90)

for (i in 1:90) {

  for (j in 1:nrow(subset(mpres08, mpres08$DaysToEday <= 90))){
       
  if(mpres08$PriceD[j] > mpres08$PriceR[j]) {
    Obama08.ECvotesByDay[i] <- Obama08.ECvotesByDay[i] mpres08$EV[j]

  }

  else {

    McCain08.ECvotesByDay[i] <- McCain08.ECvotesByDay[i] mpres08$EV[j]

  }
  }
}

dput of Data (five rows)

structure(list(state = c("AK", "AK", "AK", "AK", "AK"), state.name = c("Alaska", 
"Alaska", "Alaska", "Alaska", "Alaska"), Obama = c(38L, 38L, 
38L, 38L, 38L), McCain = c(59L, 59L, 59L, 59L, 59L), EV = c(3L, 
3L, 3L, 3L, 3L), X = c(24073L, 25195L, 8773L, 25603L, 25246L), 
    day = structure(c(13937, 13959, 13637, 13967, 13960), class = "Date"), 
    PriceD = c(7.5, 7.5, 10, 8, 7.5), VolumeD = c(0L, 0L, 0L, 
    0L, 0L), PriceR = c(92.5, 92.5, 90, 92, 92.5), VolumeR = c(0L, 
    0L, 0L, 0L, 0L), DaysToEday = c(250, 228, 550, 220, 227)), row.names = c(NA, 
5L), class = "data.frame")

CodePudding user response:

You are adding a number to NA, and for R the result is NA.

CodePudding user response:

Obama08.ECvotesByDay[i] and McCain08.ECvotesByDay[i] are initialised with NA. In R, if you try to do arithmetic with NA it stays NA (e.g. NA 1 results in NA). Depending on what is a neutral result for you, you could initialise the vectors in the beginning with 0:

Obama08.ECvotesByDay <- McCain08.ECvotesByDay <- rep(0, 90)
  • Related