Home > front end >  Creating a new column based on the values of other two colum in r
Creating a new column based on the values of other two colum in r

Time:07-06

I'm having the following question for my dataset, I have one column which store participants' choice either left or right, and another two columns store what the left and the right option stands for.

For example, if the first column equals 1 (left), and the other two columns store left = Masked Picture, right = Unmaksed Picture. So, in this case, I will know this participant selected the masked picture.

Main_task Left_option Right_option (The column I want creat)
1(Left)     Masked       Unmasked        Masked
2(Right)    Unmasked       Masked        Masked
1(Left)     Unmasked       Masked        Unmasked
2(Right)    Masked       Unmasked        Unmasked
2(Right)

Since I have a large dataset, I'm wondering how could create a new column based on these columns?

Your help will be much appreciated! Thanks

CodePudding user response:

A possible solution:

library(dplyr)

df %>% 
  mutate(new = if_else(Main_task == "1(Left)", Left_option, Right_option))

#>   Main_task Left_option Right_option      new
#> 1   1(Left)      Masked     Unmasked   Masked
#> 2  2(Right)    Unmasked       Masked   Masked
#> 3   1(Left)    Unmasked       Masked Unmasked
#> 4  2(Right)      Masked     Unmasked Unmasked
  •  Tags:  
  • r
  • Related