简体   繁体   中英

Creating a new column based on the values of other two columns in r

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 to create)
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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM