this question has answer here:
- how reshape data long wide format? 7 answers
i have data frame several data this
key b c 1 1 2 3 1 4 6 8 1 3 2 1
i need merge these data same key 1 row this
key a1 b1 c1 a2 b2 c2 a3 b3 c3 1 1 2 3 4 6 8 3 2 1
is there easy way result need.
if single group of 'key', 1 option use base r
. transpose (t
) dataset except first column (df[-1]
), concatenate vector
, convert data.frme
, cbind
first element of first column.
res <- cbind(df1[1,1], as.data.frame.list(c(t(df1[-1])))) names(res) <- c(names(df1)[1] ,make.unique(rep(names(df1)[-1],3))) res # key b c a.1 b.1 c.1 a.2 b.2 c.2 #1 1 1 2 3 4 6 8 3 2 1
or use data.table
i.e. development version v1.9.7
if there many 'key' elements
library(data.table) dcast(setdt(df1), key~rowid(key), value.var = c("a", "b", "c"),sep="") # key a1 a2 a3 b1 b2 b3 c1 c2 c3 #1: 1 1 4 3 2 6 2 3 8 1
if have data.table
version < v1.9.7, need create sequence column grouped 'key'.
dcast(setdt(df1)[, rn := 1:.n , key], key ~rn, value.var = c("a", "b", "c"),sep="") # key a1 a2 a3 b1 b2 b3 c1 c2 c3 #1: 1 1 4 3 2 6 2 3 8 1
Comments
Post a Comment