For each row return the column name of the largest value

前端 未结 8 2277
礼貌的吻别
礼貌的吻别 2020-11-21 07:06

I have a roster of employees, and I need to know at what department they are in most often. It is trivial to tabulate employee ID against department name, but it is trickier

8条回答
  •  花落未央
    2020-11-21 08:02

    A simple for loop can also be handy:

    > df<-data.frame(V1=c(2,8,1),V2=c(7,3,5),V3=c(9,6,4))
    > df
      V1 V2 V3
    1  2  7  9
    2  8  3  6
    3  1  5  4
    > df2<-data.frame()
    > for (i in 1:nrow(df)){
    +   df2[i,1]<-colnames(df[which.max(df[i,])])
    + }
    > df2
      V1
    1 V3
    2 V1
    3 V2
    

提交回复
热议问题