0

Example data:

df <- data.frame(one = c(T, F, F, F, F, T), 
                 two = c(F, F, F, F, T, F), 
                 three = c(F, T, T, T, F, F))  

The real data has more columns but this will do as an example. I need a function that turns df in the following data frame:

data.frame(type = c('one', 'three', 'three', 'three', 'two', 'one'))

I looked at stack and melt and a couple of weird workarounds like the following:

df.new <- data.frame(type = c(rep.int(NA, 6)))
for(i in 1:ncol(df)) {
  df.new[,1] <- ifelse(df[,i], colnames(df)[i], df.new[,1])
}
df.new

But is there a function that does this?

989
  • 12,579
  • 5
  • 31
  • 53
Dutchmv
  • 126
  • 7

1 Answers1

1

Try this vectorized using max.col in base R:

data.frame(type=names(df)[max.col(df)])

   # type
# 1   one
# 2 three
# 3 three
# 4 three
# 5   two
# 6   one
989
  • 12,579
  • 5
  • 31
  • 53