How would I reshape this kind of data? This is just a short exercpt of my data, the real dataset is much longer. So an automated solution for any kind of lengh would be very appreciated.
data <- data.frame(id = c(1,2,3),
volume_1 = c(0.33, 0.58, 0.2),
name_1 = c("a", "b","c"),
volume_2 = c(0.3, 0.4, 0.5),
name_2 = c("x", "y", "z")
)
data
id volume_1 name_1 volume_2 name_2
1 1 0.33 a 0.3 x
2 2 0.58 b 0.4 y
3 3 0.20 c 0.5 z
to this:
foo <- data.frame(id = c(1,2,3),
a = c(0.33, 0, 0),
b = c(0, 0.58, 0),
c = c(0, 0, 0.2),
x = c(0.3, 0, 0),
y = c(0, 0.4, 0),
z = c(0, 0, 0.5)
)
foo
id a b c x y z
1 1 0.33 0.00 0.0 0.3 0.0 0.0
2 2 0.00 0.58 0.0 0.0 0.4 0.0
3 3 0.00 0.00 0.2 0.0 0.0 0.5
I´m aware of pivot_longer() or pivot_wider() and also of the reshape package, but I´m not sure how to accomplish this with any kind of length in the dataset.