Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recode based on TRUE or FALSE in another variable

Tags:

r

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

like image 274
Ed G Avatar asked Dec 01 '22 22:12

Ed G


2 Answers

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 1s and 2s. The values in value are divided by the values in this new vector. A division by one does not change the original values.

like image 51
Sven Hohenstein Avatar answered Dec 21 '22 23:12

Sven Hohenstein


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))
like image 21
Sacha Epskamp Avatar answered Dec 22 '22 00:12

Sacha Epskamp