Dataframe create new column based on other columns

后端 未结 5 452
既然无缘
既然无缘 2020-12-05 15:33

I have a dataframe:

df <- data.frame(\'a\'=c(1,2,3,4,5), \'b\'=c(1,20,3,4,50))
df
    a    b
1   1    1
2   2   20
3   3    3
4   4    4
5   5   50
         


        
5条回答
  •  一向
    一向 (楼主)
    2020-12-05 16:10

    Here is a slightly more confusing algebraic method:

    df$c <- with(df, b + ((-1)^((a==b)+1) * a))
    
    df
      a  b  c
    1 1  1  2
    2 2 20 18
    3 3  3  6
    4 4  4  8
    5 5 50 45
    

    The idea is that the "minus" operator is turned on or off based on the test a==b.

提交回复
热议问题