Home > OS >  How to create new column conditioned on another column in R?
How to create new column conditioned on another column in R?

Time:07-20

Lets, say I have data:

df <- data.frame (RR_Code  = c( "848140", "848180", "848190", "848310", "848360", "848410", "848490", "850131", "850132", "850133"),
                  Model = c("X1", "FG", "FD", "XR", "RT", "FG", "CV", "GH", "ER", "RF"))

   RR_Code Model
1   848140    X1
2   848180    FG
3   848190    FD
4   848310    XR
5   848360    RT
6   848410    FG
7   848490    CV
8   850131    GH
9   850132    ER
10  850133    RF

Now I want to create a new column based on filer.df and if RR_Code is included in filter.df, its 1, otherwise 0.

filter.df <- c("848410", "848490", "850131", "850132")

Expected outcome:

   RR_Code Model filter
1   848140    X1      0
2   848180    FG      0
3   848190    FD      0
4   848310    XR      0
5   848360    RT      0
6   848410    FG      1
7   848490    CV      1
8   850131    GH      1
9   850132    ER      1
10  850133    RF      0

CodePudding user response:

We can do

df$filter <-  (df$RR_Code %in% filter.df)

df
#   RR_Code Model filter
#1   848140    X1      0
#2   848180    FG      0
#3   848190    FD      0
#4   848310    XR      0
#5   848360    RT      0
#6   848410    FG      1
#7   848490    CV      1
#8   850131    GH      1
#9   850132    ER      1
#10  850133    RF      0

CodePudding user response:

There are several ways of doing it, my first intuition would be using case_when, from dplyr.

df$new_column <- case_when(df$RR_Code %in% filter.df ~ 1,
                           TRUE ~ 0)

Which would return:

       RR_Code Model new_column
1   848140    X1          0
2   848180    FG          0
3   848190    FD          0
4   848310    XR          0
5   848360    RT          0
6   848410    FG          1
7   848490    CV          1
8   850131    GH          1
9   850132    ER          1
10  850133    RF          0
  • Related