【问题标题】:Creating a new column based on the values of other two colum in r根据 r 中其他两列的值创建新列
【发布时间】:2022-07-05 17:41:09
【问题描述】:

我的数据集有以下问题,我有一列存储参与者的选择是左还是右,另外两列存储左右选项代表什么。

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

由于我有一个大型数据集,我想知道如何根据这些列创建一个新列?

您的帮助将不胜感激! 谢谢

【问题讨论】:

  • df$new_col <- ifelse(df$Main_task == "1(Left)", df$Left_option, df$Right_option)

标签: r rstudio


【解决方案1】:

一个可能的解决方案:

library(tidyverse)

df %>% 
  mutate(new = if_else(str_detect(Main_task, "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

【讨论】:

    猜你喜欢
    • 2023-01-24
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多