3

I'd like to create columns in a data frame based on the unique values from a single column.

E.g.

Column1
A
B
C

Into

A     B      C
True  False  False
False True   False
False False  True
Cam
  • 133
  • 5

3 Answers3

5

We can use table

!!table(1:nrow(df1), df1$Column1)
#       A     B     C
#  1  TRUE FALSE FALSE
#  2 FALSE  TRUE FALSE
#  3 FALSE FALSE  TRUE

Or using mtabulate from qdapTools

library(qdapTools)
mtabulate(df1$Column1)!=0
#         A     B     C
#[1,]  TRUE FALSE FALSE
#[2,] FALSE  TRUE FALSE
#[3,] FALSE FALSE  TRUE

Or using model.matrix

 model.matrix(~Column1-1, df1)!=0
 #  Column1A Column1B Column1C
 #1     TRUE    FALSE    FALSE
 #2    FALSE     TRUE    FALSE
 #3    FALSE    FALSE     TRUE
akrun
  • 874,273
  • 37
  • 540
  • 662
5

You could also use a loop,

sapply(df$Column1, function(i) grepl(i, df$Column1))
#         A     B     C
#[1,]  TRUE FALSE FALSE
#[2,] FALSE  TRUE FALSE
#[3,] FALSE FALSE  TRUE
Sotos
  • 51,121
  • 6
  • 32
  • 66
2

You can also use dcast from reshape2 package

library(reshape2)
!is.na(dcast(df, Column1 ~ Column1))[, -1]

#       A     B     C
#[1,]  TRUE FALSE FALSE
#[2,] FALSE  TRUE FALSE
#[3,] FALSE FALSE  TRUE
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213