How to populate dataset 0s and 1s for values ​​that correspond to row column in R?

I have a dataset in a csv file that looks like this:

 X               Colour Orange Red White Violet Black Yellow Blue
1 1          Orange, Red     NA  NA    NA     NA    NA     NA   NA
2 2                  Red     NA  NA    NA     NA    NA     NA   NA
3 3         White, Black     NA  NA    NA     NA    NA     NA   NA
4 4               Yellow     NA  NA    NA     NA    NA     NA   NA
5 5 Blue, Orange, Violet     NA  NA    NA     NA    NA     NA   NA

I am trying to add 0 and 1 for each combination of column columns. Expected Result:

      Colour     Orange Red White   Violet  Black   Yellow  Blue
1   Orange,Red   1       1    0        0      0        0      0
2   Red          0       1    0        0      0        0      0
3   White,Black  0       0    1        0      1        0      0
4   Yellow       0       0    0        0      0        1      0
5   Blue,Orange, 1       0    0        1      0        0      1
    Violet

How to achieve this in R?

+4
source share
2 answers

Scroll through the list of column names and see if they are in the template using grepl:

dat[-(1:2)] <-  sapply( colnames(dat[-(1:2)]), grepl, x=dat$Colour  ) + 0

#  X               Colour Orange Red White Violet Black Yellow Blue
#1 1          Orange, Red      1   1     0      0     0      0    0
#2 2                  Red      0   1     0      0     0      0    0
#3 3         White, Black      0   0     1      0     1      0    0
#4 4               Yellow      0   0     0      0     0      1    0
#5 5 Blue, Orange, Violet      1   0     0      1     0      0    1
+6
source

Not sure if you added NA columns or not. Even without any identification columns NA, we can use the strsplit"Color" column to separate the column, apply it mtabulatein the list output and, if necessary, change the output order based on the "dat" column names

library(qdapTools)
cbind(dat[1:2], mtabulate(strsplit(dat$Colour, ', ')))[names(dat)]
#   X               Colour Orange Red White Violet Black Yellow Blue
#1 1          Orange, Red      1   1     0      0     0      0    0
#2 2                  Red      0   1     0      0     0      0    0
#3 3         White, Black      0   0     1      0     1      0    0
#4 4               Yellow      0   0     0      0     0      1    0
#5 5 Blue, Orange, Violet      1   0     0      1     0      0    1

cSplit_e splitstackshape

library(splitstackshape)
cSplit_e(dat[1:2], 'Colour', type='character', fill=0)
+3

All Articles