lundi 29 janvier 2018

ifelse inside for loop w/ 2 conditions

I'm sorry if this has been asked before. I have checked numerous questions about using if-else inside for loops to no avail. I must be misinterpreting the answers. I've edited my code multiple times to avoid different fatal errors and/or unanticipated outputs (incl. no change and/or only the else statement being evaluated). Below are my two attempts at using ifelse.

What I want the loop to do: Check if Column A has a negative value and Column B is equal to 2. If both conditions are true, put a 0 in Column C; otherwise, copy the value from Column B as is to Column C. Ultimately, I also want to do the reverse - swap 0s for 2s when Column A is negative.

Thanks!

condition = c(0,1,2)
ppt1 = sample(condition, 124, replace = T) 
ES = rnorm(n = 124)
key = as.data.frame(cbind(ES,ppt1))
key$recoded = rep(NA, 124)

for(i in nrow(key)){ 
  ifelse((key$ES[i] < 0) && (key$ppt1[i] == 2),key$recoded[i] == 0,key$recoded[i] == key$ppt1[i]) 
}

for (i in 1:nrow(key)) {
  if(key$ES[i] < 0 && key$ppt1 == 2) {
    key$recoded[i] == 0
  } else {
    key$recoded[i] == "key"
  }
}

Aucun commentaire:

Enregistrer un commentaire