How do change the choice value in a choiceset using R?

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

Answers (1)

akrun
akrun

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 <- data.frame(mode=c("car","car","car","car"),
    choice = c(1,0, 0,0),mainmode = c("BS","car","active","TX"), 
        stringsAsFactors = FALSE)

Upvotes: 1

Related Questions