【问题标题】:How can I create a new column with values 1/0, where the value in the new column is 1 only if values in two other columns are both 1?如何创建一个值为 1/0 的新列,其中仅当其他两个列中的值均为 1 时新列中的值为 1?
【发布时间】:2023-01-19 01:22:21
【问题描述】:

我在 DF 中有两列,“湿”和“冷”,值分别为 1 和 0,例如:

Wet Cold

1     1

0     1

0     1

1     0

1     1

0     0

我想创建一个新列 wet&cold,仅当 wet=1 时冷=1,然后湿&冷=1。如果其中任何一个或两个都为 0 或不匹配,则 wet&cold=0。

我尝试使用 grepl 解决问题,但没有成功。

【问题讨论】:

    标签: r grepl


    【解决方案1】:

    基础 R 解决方案

    df$`wet&cold` <- df$Wet*df$Cold
    df
    
      Wet Cold wet&cold
    1   1    1        1
    2   0    1        0
    3   0    1        0
    4   1    0        0
    5   1    1        1
    6   0    0        0
    

    dplyr解决方案

    df %>%
      mutate(`wet&cold`=Wet*Cold)
    
      Wet Cold wet&cold
    1   1    1        1
    2   0    1        0
    3   0    1        0
    4   1    0        0
    5   1    1        1
    6   0    0        0
    

    【讨论】:

      猜你喜欢
      • 2021-12-07
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-24
      • 1970-01-01
      相关资源
      最近更新 更多