3

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 this

int letter

1    y
2    x
3    z

my code is:

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

but it is not showing the second column and i need save in a new data.frame, any suggestion? thanks.

4

3 に答える 3

5

使用できます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
于 2013-09-30T06:21:18.933 に答える
0

この同様の質問に対する解決策。

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)
  })
于 2017-01-01T15:59:56.610 に答える