簡體   English   中英

根據 r 中其他兩列的值創建新列

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

我的數據集有以下問題,我有一列存儲參與者的選擇左側或右側,另外兩列存儲左右選項代表的內容。

例如,如果第一列等於 1(左),而其他兩列存儲 left = Masked Picture,right = Unmaksed 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)

由於我有一個大型數據集,我想知道如何根據這些列創建一個新列?

您的幫助將不勝感激!

謝謝

一個可能的解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM