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
:
df$newVals <- with(df, value / (tf + 1))
How it works?
If boolean values (like tf
) are used with mathematical operators, they are cast into numeric values (FALSE
is transformed to 0
and TRUE
is transformed to 1
). Hence the command tf + 1
creates a numeric vector of 1
s and 2
s. The values in value
are divided by the values in this new vector. A division by one does not change the original values.
You can do this with ifelse
:
value<-c(2, 4, 5, 8, 2, 3, 1)
tf<-c(TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE)
df<-data.frame(value, tf)
df$newVals <- with(df, ifelse(tf, value/2, value))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With