Dataframe create new column based on other columns

后端 未结 5 445
既然无缘
既然无缘 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:15

    A solution with apply

    myFunction <- function(x){
      a <- x[1]
      b <- x[2]
      #further values ignored (if there are more than 2 columns)
      value <- if(a==b) a + b else b - a
      #or more complicated stuff
      return(value)
    }
    
    df$c <- apply(df, 1, myFunction)
    

提交回复
热议问题