小编skl*_*lal的帖子

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

我有两列,比如 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)

swap if-statement r function conditional-statements

1
推荐指数
1
解决办法
630
查看次数

标签 统计

conditional-statements ×1

function ×1

if-statement ×1

r ×1

swap ×1