Reputation: 15
I have a quite big dataframe with the following structure:
image coef v3 v4 v5 v6 ... v20
1 A 0 1 2 3
1 B 2 4 6 5
1 C 1 2 4 7
1 D 4 5 6 4
2 A 2 3 4 5
2 B 2 3 4 5
2 C 2 3 4 5
2 D 2 3 4 5
And I need to end up with "flattened" structure on the coef variable for each image index. Now each image have the variables with the shape [4:20] but i need it to be [1:80] with the patern [A,B,C,D,A',B',C',D'...]. like this:
image v3 v4 v5 v6 v7 v8 v9 v10 ... v80
1 0 2 1 4 1 4 2 5
2 2 2 2 2 3 3 3 3
I tried to do:
reshape(df, timevar = "coef", idvar = "image", direction = "wide")
But i gives me the Error :
Error in data[, timevar] : subindex out of bounds
Also I tried the library Reshape2 with:
dcast(df, image~coef, value.var= )
but since I have more than one value.var column I cannot figure out how to do it.
Upvotes: 1
Views: 201
Reputation: 887391
We can melt
and then do the dcast
library(data.table)
dM <- melt(setDT(df1), id.var=c("image", "coef"))
dcast(dM, image~variable+coef, value.var="value")
Or use recast
(which is a wrapper for melt/dcast
) from reshape2
library(reshape2)
recast(df1, id.var=c("image", "coef"),image~variable+coef, value.var="value")
# image v3_A v3_B v3_C v3_D v4_A v4_B v4_C v4_D v5_A v5_B v5_C v5_D v6_A v6_B v6_C v6_D
#1 1 0 2 1 4 1 4 2 5 2 6 4 6 3 5 7 4
#2 2 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5
df1 <- structure(list(image = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L),
coef = c("A",
"B", "C", "D", "A", "B", "C", "D"), v3 = c(0L, 2L, 1L, 4L, 2L,
2L, 2L, 2L), v4 = c(1L, 4L, 2L, 5L, 3L, 3L, 3L, 3L), v5 = c(2L,
6L, 4L, 6L, 4L, 4L, 4L, 4L), v6 = c(3L, 5L, 7L, 4L, 5L, 5L, 5L,
5L)), .Names = c("image", "coef", "v3", "v4", "v5", "v6"),
class = "data.frame", row.names = c(NA, -8L))
Upvotes: 1