Using mutate command of Tidyverse package to convert discrete binary choices into Logical one

Hi,
I am trying to convert my discrete binary choices (car , bus) into logical format (Car = True, Bus = False) using mutate command associated with Tidyverse package. Could someone help me with a proper code?

library(tidyverse)

(df <- data.frame(v1 = c("car", "bus", "car")))
mutate(df,
v2 = v1=="car")

Just for fun: If you have more than two choices, you could do the following:

library(tidyverse)

df <- tibble(CHOICE = c("car", "bus", "bus", "truck", "car", "bus"))

df %>% 
    cbind(map_dfc(unique(df$CHOICE), ~tibble(!!.x := .x))) %>% 
    mutate_at(vars(-CHOICE), function(.x) {.x == .$CHOICE})

Result:

  CHOICE   car   bus truck
1    car  TRUE FALSE FALSE
2    bus FALSE  TRUE FALSE
3    bus FALSE  TRUE FALSE
4  truck FALSE FALSE  TRUE
5    car  TRUE FALSE FALSE
6    bus FALSE  TRUE FALSE

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.