1

我正在尝试为 data.frame 中的每一行选择具有最高值的列。例如,数据就是这样设置的。

> df <- data.frame(one = c(0:6), two = c(6:0))
> df
  one two 
1   0   6
2   1   5
3   2   4
4   3   3
5   4   2
6   5   1
7   6   0

然后我想根据这些行设置另一列。数据框看起来像这样。

> df
  one two rank 
1   0   6    2
2   1   5    2
3   2   4    2
4   3   3    3
5   4   2    1
6   5   1    1
7   6   0    1

我想有某种方法可以在这里使用 plyr 或 sapply ,但目前它正在躲避我。

4

1 回答 1

5

可能有更有效的解决方案,但是

ranks <- apply(df, 1, which.max)
ranks[which(df[, 1] == df[, 2])] <- 3

编辑:适当间隔!

于 2013-05-13T18:10:25.300 回答