R 获取每行具有最大值的列的名称

R 获取每行具有最大值的列的名称,r,R,我需要你的帮助,我有一个这样的数据框 int x y z 1 0 1 0 2 1 0 0 3 0 0 1 int letter 1 y 2 x 3 z 我需要的结果一定是这样 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:nco

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

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

1    y
2    x
3    z
我需要的结果一定是这样

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中,有什么建议吗?谢谢。

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

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

示例您可以使用
max.col

dat$newcol <- names(DF)[-1][max.col(DF[-1])]
类似问题的解决方案

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)
  })
tdf%
lapply(总和)%>%
(功能(x){

a+1.你比我快。但是我的答案是用
names()[zzz]
而不是
colnames(zzz[])
zzz[,idx]
而不是
zzz[idx]
,所以我就不说了!