Get names of column with max value for each row

后端 未结 3 1825
醉酒成梦
醉酒成梦 2020-12-07 04:05

i need your help, i have a data frame like this

int x  y  z
1   0  1  0
2   1  0  0
3   0  0  1

and the result that i need must be like thi

相关标签:
3条回答
  • 2020-12-07 04:24

    You can use max.col:

    dat$newcol <- names(DF)[-1][max.col(DF[-1])]
    

    This gives

      int x y z newcol
    1   1 0 1 0      y
    2   2 1 0 0      x
    3   3 0 0 1      z
    
    0 讨论(0)
  • 2020-12-07 04:25

    A solution to this similar question.

    tdf <- data.frame(
      A = c(1,1,0,0),
      B = c(0,0,1,0),
      C = c(0,0,0,1)
    )
    
    library(magrittr)
    
    tdf %>%
      lapply(sum) %>%
      (function(x){
        a <- c()
        for(i in 1:length(x)){
          a <- c(a, rep(names(x[i]), x[i]))
        }
        return(a)
      })
    
    0 讨论(0)
  • 2020-12-07 04:38

    I'm sure there are plenty of ways, but here's one:

    samples <- read.table(text="int x  y  z
    1   0  1  0
    2   1  0  0
    3   0  0  1",
    header=TRUE)
    
    #  int x y z
    #1   1 0 1 0
    #2   2 1 0 0
    #3   3 0 0 1
    
    data.frame(
     samples[1],
     letter=colnames(samples[-1][apply(samples[-1],1,which.max)])
    )
    
    #  int letter
    #1   1      y
    #2   2      x
    #3   3      z
    
    0 讨论(0)
提交回复
热议问题