datanew datanew - 27 days ago 11
R Question

How to convert a long data frame to a wide data frame with duplicates/triplicates?

Consider I have a data frame in long format with three columns. Column

x
contains the measurements,
y
the names of the 3 variables, and
z
contains 2 levels. There are duplicate measurements for each of the
y
variables:

df <- data.frame(x=c(1:12), y=rep(0:2, 4), z=rep(letters[1:2], 6))
df$y <- as.factor(df$y)
df <- arrange(df, y, z)
df

x y z
1 1 0 a
2 7 0 a
3 4 0 b
4 10 0 b
5 5 1 a
6 11 1 a
7 2 1 b
8 8 1 b
9 3 2 a
10 9 2 a
11 6 2 b
12 12 2 b


How can I get
df_wide
like this?

z 0 1 2
a 1 5 3
a 7 11 9
b 4 2 6
b 10 8 12

d.b d.b
Answer Source
do.call(cbind, lapply(split(df, df$y), function(a)
    setNames(object = data.frame(a$x,
                                 row.names = paste0(as.character(a$z), 1:NROW(a))),
             nm = a$y[1])))
#    0  1  2
#a1  1  5  3
#a2  7 11  9
#b3  4  2  6
#b4 10  8 12