Reputation: 1171
Is it possible to obtain multiple outputs with ifelse
?
I would like to create a variable ExpectedVariable
with either 0s or 1s.
If VariableA
has a value of 0, then I need ExpectedVariable
to be 0 for the current row and for the previous row. If VariableA
has a value of 1, then I need ExpectedVariable
to be 1.
I was thinking of something like this (which as it is doesn't work):
mydata$ExpectedVariable <- ifelse(mydata$VariableA == 0, (mydata$ExpectedVariable & lag(mydata$ExpectedVariable) <- 0), 1)
Example:
VariableA ExpectedVariable
row1 1 1
row2 1 1
row3 1 1
row4 1 1
row5 1 1
row6 1 0
row7 0 0
row8 1 1
row9 1 0
row10 0 0
row11 1 1
row12 1 1
row13 1 0
row14 0 0
Upvotes: 0
Views: 1787
Reputation: 7830
Should do the trick :
df$expectedVariable[df$VariableA == 1] <- 1
df$expectedVariable[df$VariableA == 0] <- 0
df$expectedVariable[which(df$VariableA == 0) - 1] <- 0
Or with the 2 last lines in one :
df$expectedVariable[c(which(df$VariableA == 0), which(df$VariableA == 0) - 1)] <- 0
Upvotes: 0
Reputation: 16920
Another way you can think about your problem is that ExpectedVariable
will equal zero if either of two conditions are met (current value of VariableA
is zero, or the lead of VariableA
is zero). In other words, instead of thinking of multiple outputs, think of multiple conditions, which ifelse()
can easily do. Then we can accomplish this with any sort of shifting function.
Using data.table::shift()
:
expected_df <- read.table(header = TRUE, text = "
VariableA ExpectedVariable
row1 1 1
row2 1 1
row3 1 1
row4 1 1
row5 1 1
row6 1 0
row7 0 0
row8 1 1
row9 1 0
row10 0 0
row11 1 1
row12 1 1
row13 1 0
row14 0 0")
rownames(expected_df) <- NULL
mydata <- data.frame(VariableA = expected_df$VariableA)
mydata$ExpectedVariable <- ifelse(mydata$VariableA == 0
| data.table::shift(mydata$VariableA,
type = 'lead') == 0,
0, 1)
all.equal(mydata, expected_df)
[1] TRUE
Using dplyr::lead()
mydata$ExpectedVariable <- ifelse(mydata$VariableA == 0
| dplyr::lead(mydata$VariableA) == 0,
0, 1)
all.equal(mydata, expected_df)
[1] TRUE
Upvotes: 1