Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

I have the following data frame named DF in r:

            1         2         3    

1   VW        Mercedes   Audi                                    

2   Porsche   BMW       VW                                                    

3   Audi     Honda     Toyota                                             

4  Dodge     Opel      VW                                     

5  Lexus     Volvo     BMW                                                      

6  Dodge     VW       Porsche 

i want to create a new dataframe (DF2) where each element of DF are the column names of new data frame and column names of DF are elements of DF2:

     Audi  BMW  Dodge  Honda  Lexus  Mercedes  Opel  Porsche Toyota  Volvo  VW

1    3     0     0     0      0       2         0      0        0     0    1

2    0     2     0     0     0        0         0       1       0     0    3

3    1     0     0     2     0        0         0       0       3     0    0 

4    0     0     1     0     0        0         2       0       3     0    3     

5    0     3     0     0     1        0        0        0       0     2    0

6    0     0     1     0     0        0        0        3       0     0    2

1 Answer

0 votes
by (41.4k points)

Here is a solution of your question using  acast from reshape2

library(reshape2)

acast(melt(as.matrix(df)), Var1~value, value.var='Var2', fill=0)

   Audi BMW Dodge Honda Lexus Mercedes Opel Porsche Toyota Volvo VW

#1   3    0    0     0     0      2      0     0       0     0     1

#2   0    2    0     0     0      0      0     1       0     0     3

#3   1    0    0     2     0      0      0     0       3     0     0

#4   0    0    1    0      0      0      2     0       0     0     3

#5   0    3    0    0      1      0      0     0       0     2     0

#6  0     0    1    0      0      0      0     3       0     0     2

If you wish to learn about R Programming then visit this R Programming Course.

Browse Categories

...