0

I have a data like this:

structure(list(ID = 1:4, concept = c("a", "b", "c", "d"), count = c(1L, 
2L, 4L, 6L)), class = "data.frame", row.names = c(NA, -4L))

How can I reshape the data to have :


ID  a   b   c   d
1   1   0   0   0
2   0   2   0   0
3   0   0   4   0
4   0   0   0   6
Ali Roghani
  • 495
  • 2
  • 7
  • 3
    `library(tidyverse) df %>% pivot_wider(ID, names_from = concept, values_from = count, values_fill = 0)` ? – PaulS Jul 08 '22 at 18:16

1 Answers1

3

You can use the following code:

df <- structure(list(ID = 1:4, concept = c("a", "b", "c", "d"), count = c(1L, 
                                                                          2L, 4L, 6L)), class = "data.frame", row.names = c(NA, -4L))

library(reshape2)
dcast(df, ID ~ concept, value.var = "count", fill = 0)
#>   ID a b c d
#> 1  1 1 0 0 0
#> 2  2 0 2 0 0
#> 3  3 0 0 4 0
#> 4  4 0 0 0 6

Created on 2022-07-08 by the reprex package (v2.0.1)

Quinten
  • 35,235
  • 5
  • 20
  • 53