Search code examples
rfunctionif-statementconditional-statementsswap

How to swap two columns in R based on a specific condition?


I have two columns,say, a & b, and I have to swap the values of a & b if the value in column b is greater than the value in column a.

I've written a function to swap the variable if the condition is met

a     b
110   70
120   80 
80    110 

swap_if<- function (a, b,missing=NA) 
{
  if(b>a)
  {
    a = a + b
    b = a - b
    a = a - b
  }
}  


swap_if(a,b)



The output should come as :

a     b
110   70
120   80 
110   80 

But I'm getting an error

the condition has length > 1 and only the first element will be used

Solution

  • If it's only 2 columns, pmin and pmax are your friends here.

    temp_min = pmin(df$a, df$b)
    df$a = pmax(df$a, df$b)
    df$b = temp_min
    

    If it's more than 2 columns, than the apply sort scales better.