Home > Mobile >  reshape data frame into colnames and rownames
reshape data frame into colnames and rownames

Time:12-06

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

CodePudding user response:

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

CodePudding user response:

Tidyverse solution

library(tidyverse) 

df %>% 
  count(cars, colour) %>% 
  pivot_wider(names_from = cars, values_from = n)

# A tibble: 3 x 4
  colour  car1  car2  car4
  <chr>  <int> <int> <int>
1 red        1    NA    NA
2 blue      NA     1    NA
3 black     NA    NA     1
  • Related