0

I want to create logical variables for every level of factor x.

so from a factor x <- factor(c('apple','orange','apple','peach')) I would get three variables each the length of x:

apple = c(T,F,T,F)
orange = c(F,T,F,F)
peach = c(F,F,F,T)

Is there a function to do this?

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
WojciechF
  • 370
  • 2
  • 14

1 Answers1

1

Try this. It creates a data frame of those vectors:

x <- as.factor(c('apple','orange','apple','peach'))
df <- data.frame(sapply(levels(x), function(l) l == x))
Gopala
  • 10,363
  • 7
  • 45
  • 77
  • exactly what I needed, but would you explain what the `function(l) l==x` does? Oh I get it... so simple... – WojciechF Jan 06 '16 at 20:10
  • sapply will iterative take each level of the factor from levels(x), passes each to the function where l is one of the levels. Then, l == x is checking which of the x values match the single level passed l. This operation will return a true/false vector for that single level. – Gopala Jan 06 '16 at 20:12
  • You can try out by simply doing 'apple' == x to see. – Gopala Jan 06 '16 at 20:13