Search code examples
rdplyrreshape2

reshape data frame into colnames and rownames


My questions is self-explained by the example, but in short: I would to dcast the data frame and add 1 and NA depending on the matched that are in the original data frame. I tried reshape2::dcast(cars~colour), but this is not the output I wanted.

in

> data.frame(cars=c("car1","car2","car4"), colour=c("red","blue","black"))
  cars     colour
1 car1   red
2 car2  blue
3 car4 black

out

        car1   car2  car4
red     1      NA    NA
blue    NA     1     NA
black   NA     NA    1

Solution

  • You can try the base R table function here -

    df <- data.frame(cars=c("car1","car2","car4"), colour=c("red","blue","black"))
    
    tab <- table(df)
    tab
    #      colour
    #cars   black blue red
    #  car1     0    0   1
    #  car2     0    1   0
    #  car4     1    0   0
    

    To get it similar to your expected output you may adjust the code -

    tab <- df |> rev() |> table() |> as.data.frame.matrix()
    tab[tab == 0] <- NA
    tab
    
    #      car1 car2 car4
    #black   NA   NA    1
    #blue    NA    1   NA
    #red      1   NA   NA