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
>Solution :
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)