【问题标题】:Get names of column with max value for each row获取每行最大值的列名
【发布时间】:2013-09-30 06:12:19
【问题描述】:

我需要你的帮助,我有一个这样的数据框

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

而我需要的结果一定是这样的

int letter

1    y
2    x
3    z

我的代码是:

for (i in 1:nrow(samples)) 
    for(j in 1:ncol(samples)) 
        if(samples[i,][,j] == 1) print(c(i,names(samples[i,j])))

但它没有显示第二列,我需要保存在新的 data.frame 中,有什么建议吗?谢谢。

【问题讨论】:

    标签: r


    【解决方案1】:

    你可以使用max.col:

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

    这给了

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

    【讨论】:

      【解决方案2】:

      我相信有很多方法,但这里有一个:

      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
      

      【讨论】:

      • +1。你打败了我。但我的答案使用names()[zzz] 而不是colnames(zzz[])zzz[,idx] 而不是zzz[idx],所以我要留下它!
      【解决方案3】:

      this 类似问题的解决方案。

      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)
        })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-25
        • 2018-07-07
        • 1970-01-01
        • 2021-04-17
        • 2015-07-07
        • 2021-10-13
        相关资源
        最近更新 更多