generate column values with multiple conditions in R

后端 未结 8 2058
甜味超标
甜味超标 2020-12-29 00:22

I have a dataframe z and I want to create the new column based on the values of two old columns of z. Following is the process:

&g         


        
8条回答
  •  北荒
    北荒 (楼主)
    2020-12-29 00:43

    Here is an easy solution with just one ifelse command:

    Calculate the multiplier of t:

    ifelse(z$x == 7, 3, z$x ^ (z$x %in% c(2, 4)))
    

    The complete command:

    transform(z, q = t * ifelse(x == 7, 3, x ^ (x %in% c(2, 4))))
    
        x  y  t  q
    1   1 11 21 21
    2   2 12 22 44
    3   3 13 23 23
    4   4 14 24 96
    5   5 15 25 25
    6   6 16 26 26
    7   7 17 27 81
    8   8 18 28 28
    9   9 19 29 29
    10 10 20 30 30
    

提交回复
热议问题