如何根据每行中的最大值删除列

Vin*_*woo 1 r

Col1<-c(3,8,2,4,2)
Col2<-c(3,7,3,9,2)
Col3<-c(5,7,5,7,5)
Col4<-c(1,9,2,3,4)
Col5<-c(1,2,6,7,5)
Toy<-data.frame(Col1,Col2,Col3,Col4,Col5)

> Toy
  Col1 Col2 Col3 Col4 Col5
1    3    3    5    1    1
2    8    7    7    9    2
3    2    3    5    2    6
4    4    9    7    3    7
5    2    2    5    4    5
Run Code Online (Sandbox Code Playgroud)

给定上面的数据框,我想删除每行中等于每行最大值的值,以及最大值的右边(或增加列#).

从逻辑上讲,该声明将是:

1. Find max value per row 
2. Make max value for each row = NA
3. Make all columns to the right of column with max value =NA
Run Code Online (Sandbox Code Playgroud)

所以新的数据框架看起来像

  Col1 Col2 Col3 Col4 Col5
1    3    3    NA   NA  NA
2    8    7    7    NA  NA
3    2    3    5    2   NA
4    4    NA   NA   NA  NA
5    2    2    NA   NA  NA
Run Code Online (Sandbox Code Playgroud)

脚步

Jos*_*ien 11

这是一个apply()避免显式for循环的基础解决方案:

ff <- function(X) {X[which.max(X):length(X)] <- NA; X}
t(apply(Toy, 1, ff))
#      Col1 Col2 Col3 Col4 Col5
# [1,]    3    3   NA   NA   NA
# [2,]    8    7    7   NA   NA
# [3,]    2    3    5    2   NA
# [4,]    4   NA   NA   NA   NA
# [5,]    2    2   NA   NA   NA
Run Code Online (Sandbox Code Playgroud)