如何根据特定条件交换 R 中的两列?

skl*_*lal 1 swap if-statement r function conditional-statements

我有两列,比如 a & b,如果 b 列中的值大于 a 列中的值,我必须交换 a & b 的值。

如果满足条件,我已经编写了一个函数来交换变量

a     b
110   70
120   80 
80    110 

Run Code Online (Sandbox Code Playgroud)
swap_if<- function (a, b,missing=NA) 
{
  if(b>a)
  {
    a = a + b
    b = a - b
    a = a - b
  }
}  


swap_if(a,b)



Run Code Online (Sandbox Code Playgroud)

输出应为:

a     b
110   70
120   80 
110   80 

Run Code Online (Sandbox Code Playgroud)

但我收到一个错误

the condition has length > 1 and only the first element will be used
Run Code Online (Sandbox Code Playgroud)

Gre*_*gor 5

如果它只有 2 列,pmin并且pmax是您的朋友在这里。

temp_min = pmin(df$a, df$b)
df$a = pmax(df$a, df$b)
df$b = temp_min
Run Code Online (Sandbox Code Playgroud)

如果它超过 2 列,则应用排序比例更好。