我基本上是在Python中的np.argmax()
上寻找等效项。我有一个数据框:
> as.data.frame(matrix(runif(20, 0, 1), ncol=2))
V1 V2
1 0.42718891 0.5263497
2 0.52157661 0.8216030
3 0.63448978 0.9766504
4 0.69304632 0.6446195
5 0.29205498 0.3424074
6 0.05661658 0.3009205
7 0.39710808 0.8118707
8 0.11667427 0.1558385
9 0.81182761 0.3003825
10 0.12070549 0.4928229
我想要一个这样的因子,其中列索引的所有行的最大值都为
[1] 0 0 0 0 0 0 1 0 1 1 1 1 0 0 0
[52] 0 1 0 0 1 0 0 0 1 1 1 0 0 0 1
[103] 0 0 1 0 1 0 1 0 1 0 1 1 1 1 1
我知道解决方案已发布在S / O上。但是,它们是多行代码,并且使用多个库,因此我正在寻找一种解决方案,其中不会出现20种不同的错误。
答案 0 :(得分:2)
我们可以使用max.col
max.col(df1, 'first') - 1
df1 <- structure(list(V1 = c(0.42718891, 0.52157661, 0.63448978, 0.69304632,
0.29205498, 0.05661658, 0.39710808, 0.11667427, 0.81182761, 0.12070549
), V2 = c(0.5263497, 0.821603, 0.9766504, 0.6446195, 0.3424074,
0.3009205, 0.8118707, 0.1558385, 0.3003825, 0.4928229)),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10"))