Reputation: 45
Make this query simple: Given data = data.frame(mode=c("car","car","car","car"),choice = c(1,0, 0,0),mainmode = c("BS","car","active","TX")); where BS = Bus, car =car, active = walk, TX = taxi.
Target output = data.frame(mode = c("car","car","car","car"),choice = c(0,1, 0,0), mainmode=c("BS","car","active","TX")). In addition, if any value from "mode" does not match with any value in "mainmode", in this case choice values (i.e., c(1,0,0,0))should remain same as it is in data.
Can anyone help me? Many thanks in advance.
Upvotes: 1
Views: 24
Reputation: 887691
We can just compare (==
) the 'mainmode' and 'mode' to return a logical vector that can be coerced (+
) to binary. Here the logical vector created is 'i1', if
there are no values that are matching then return the 'choice' as it is or else do the coercion on the logical vector (+(i1)
)
i1 <- with(data, mainmode == mode)
data$choice <- if(!any(i1)) data$choice else +(i1)
data$choice
#[1] 0 1 0 0
assuming that the columns are character
class
data <- data.frame(mode=c("car","car","car","car"),
choice = c(1,0, 0,0),mainmode = c("BS","car","active","TX"),
stringsAsFactors = FALSE)
Upvotes: 1