I’m calculating a new variable based on the TRUE/FALSE status of another:
value<-c(2, 4, 5, 8, 2, 3, 1)
tf<-c(TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE)
df<-data.frame(value, tf)
The following code does what I need (halves ‘value’ if ‘tf’ is TRUE)…
df$newVals[which(df$tf)]<-df$value[which(df$tf)]/2
df$newVals[which(!df$tf)]<-df$value[which(!df$tf)]
…but it feels too complicated. Is there a simpler approach?
Thanks
Here’s a very simple solution without
ifelse:How it works?
If boolean values (like
tf) are used with mathematical operators, they are cast into numeric values (FALSEis transformed to0andTRUEis transformed to1). Hence the commandtf + 1creates a numeric vector of1s and2s. The values invalueare divided by the values in this new vector. A division by one does not change the original values.