mutate column based on external list in R [duplicate]

How can i mutate

my_df <-data.frame(A=(1:4),
                     B= c('a','b','c','d'))
list<-c('c','d','a')

I want to create a new column list_column that should state 0 and 1 values based on if column c value present in list. I am trying to do it with mutate but nothing works.
My output should be

A B list_column
1 a           1
2 b           0
3 c           1
4 d           1

  • You can use mutate(my_df, list_column = B %in% unlist(list) + 0) The %in% operator checks for membership. It normally returns TRUE/FALSE but you can use +0 to change that to 1/0.

    – 

Leave a Comment