Create binary column (0/1) based on condition in another column

前端 未结 2 1791
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 02:36

I have a column of data in a data frame

Ozone   Solar.R Wind    Temp    Month   Day
41  190 7.4 67  5   1
36  118 8   72  5   2
12  149 12.6    74  5   3
18          


        
相关标签:
2条回答
  • 2020-12-02 02:48

    You can also use ifelse which is vectorized if-else function

    mydata$NewTemp <- ifelse(mydata$Temp>0, 1, 0)
    
    0 讨论(0)
  • 2020-12-02 02:51

    You're over-thinking things. TRUE and FALSE can be coerced to 1 and 0 respectively by using as.numeric.

    mydf$Temp > 70
    # [1] FALSE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE
    as.numeric(mydf$Temp > 70)
    # [1] 0 1 1 0 0 0 0 0 0 0 1 0 0 0 0
    

    So, to create the new column, you can simply do:

    mydf$TempBin <- as.numeric(mydf$Temp > 70)
    mydf
    #    Ozone Solar.R Wind Temp Month Day TempBin
    # 1     41     190  7.4   67     5   1       0
    # 2     36     118  8.0   72     5   2       1
    # 3     12     149 12.6   74     5   3       1
    # 4     18     313 11.5   62     5   4       0
    # 5     NA      NA 14.3   56     5   5       0
    # 6     28      NA 14.9   66     5   6       0
    # 7     23     299  8.6   65     5   7       0
    # 8     19      99 13.8   59     5   8       0
    # 9      8      19 20.1   61     5   9       0
    # 10    NA     194  8.6   69     5  10       0
    # 11     7      NA  6.9   74     5  11       1
    # 12    16     256  9.7   69     5  12       0
    # 13    11     290  9.2   66     5  13       0
    # 14    14     274 10.9   68     5  14       0
    # 15    18      65 13.2   58     5  15       0
    
    0 讨论(0)
提交回复
热议问题