0

I have dataframe of id of car workshop and cars they fix:

id = c(1,2,3,4,5)
cars = c("Toyota; Fiat","Crysler","Ford; BMW; Audi", "BMW; Porsche; Audi; Fiat; Peugeot", "")
cbind.data.frame(id,cars)
  id                              cars
  1                      Toyota; Fiat
  2                           Crysler
  3                   Ford; BMW; Audi
  4 BMW; Porsche; Audi; Fiat; Peugeot
  5    

I would like to to get it into wide format of 0's and 1's. So my desired output would be:

id Toyota Fiat Crysler Ford BWM Audi Porsche Peugeot
1      1    1       0    0   0    0       0       0
2      0    0       1    0   0    0       0       0
3      0    0       0    1   1    1       0       0
4      0    1       0    0   1    1       1       1
5      0    0       0    0   0    0       0       0

I tried using dplyr::spread with sep = ";" parameter, but i dont know how to get those 0/1's as values. Help will be appreciated!

M.wol
  • 901
  • 3
  • 10
  • 21
  • 1
    One way would be : `splitstackshape::cSplit_e(df, "cars", type = "character", sep = ";", fill = 0)` where `df` would be `df <- data.frame(id,cars, stringsAsFactors = FALSE)`. There are lot of other options in the link. – Ronak Shah Apr 07 '20 at 07:44
  • That helped. Got additional question: do you know how to create long format instead of wide format from the first dataframe? I.E there would be column cars, but the ids would be multiplied by the number of unique entries of cars, so id1 would be duplicated, id2 would have one entry, id3 3 entries and so on – M.wol Apr 07 '20 at 11:07
  • Probably you should ask a new question for this as I don't think this is related to your original question. – Ronak Shah Apr 07 '20 at 11:51

0 Answers0