比较三列并在R数据框中创建一个新列

时间:2015-04-11 12:05:27

标签: r function dataframe warnings

我有一个如下所示的数据集:

ID  A       B       C
1   150529  148914  60277
2   328122  330293  531977
3   74310   78129   34038
4   97520   104695  55268

我正在尝试评估每一行并确定最高的数字,并在此数据集中创建一个新列,并提供答案,以便我可以在此基础上继续聚合。

我创建了一个如下所示的函数:

winner <-function(a, b, c){
  if (a>b & a>c) 
    {return("blue")} 
  else if(b>a & b>c) 
    {return("red")}
  else 
    {return("yellow")}  
} 

如果我在命令行中运行它,但是如果以下列形式使用它,则该函数有效:

res <- transform(res, newcol=winner(PAN,PRI,PRD))

我收到如下所示的错误,newcol获取所有行的值“blue”:

Warning message:
In if (a > b & a > c) { :
  the condition has length > 1 and only the first element will be used

2 个答案:

答案 0 :(得分:4)

感谢所有人,@ alexis_laz给出了我的问题的确切解决方案。

我已将代码更改为:

res <- transform(res, newcol=c("blue", "red", "yellow")[max.col(res[-1])])

它按预期工作,给出了正确的结果。 再次感谢所有人!

答案 1 :(得分:2)

尝试:

transform(res, newcol=apply(res[-1],1,max))
#  ID      A      B      C newcol
#1  1 150529 148914  60277 150529
#2  2 328122 330293 531977 531977
#3  3  74310  78129  34038  78129
#4  4  97520 104695  55268 104695

此解决方案也快于apply

transform(res, newcol=do.call(pmax, res[-1]))
相关问题