Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the column names for each row which meets a condition [duplicate]

Tags:

r

apply

d <- structure(
  list(
    Cl = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), 
    SaCl = c(0, 1, 0, 0,0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0), 
    SiCl = c(0L,0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,0L, 0L, 0L), 
    ClLo = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), 
    SiClLo = c(0L, 0L, 0L,0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), 
    SaClLo = c(1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1), 
    SaLo = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), 
    SaSiLo = c(0L, 0L,0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), 
    SiLo = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), 
    LoSa = c(0L, 0L, 0L, 0L,0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), 
    Sa = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,0L, 0L, 0L, 0L, 0L, 0L, 0L)
  ), 
  row.names = c(NA, 20L),
  class = "data.frame"
)

Each row has only one 1. I want to extract the column name which has 1 for each row such that my dataframe looks like

row.id | names
-------+-------
     1 | SaClLo
     2 | SaCl
     3 | SaClLo
     4 | SaClLo

I tried to run a function to each row

apply(d, 1, function(x) colnames(x)[x == 1])

This is giving me NULL.

like image 532
89_Simple Avatar asked Jan 01 '26 20:01

89_Simple


1 Answers

Use max.col to find the positions of the 1s and use this vector to select the respective column names.

data.frame(row.id = 1:nrow(d),
           names = names(d)[max.col(d)])
#   row.id  names
#1       1 SaClLo
#2       2   SaCl
#3       3 SaClLo
#4       4 SaClLo
#...
like image 127
markus Avatar answered Jan 03 '26 10:01

markus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!