r - Melt and cast data table using pattern -


the data.table package added new feature melt data multiple columns simultaneously. useful, can't figure out how preserve "suffix" of pre-melted variable names. example:

library(data.table)  # create data table dt <- data.table(id = seq(3), a_3 = seq(3), a_4 = seq(4, 6), b_3 = seq(7, 9), b_4 = seq(10, 12))  # melt , cast in 1 step using new feature m1 <- melt(dt, id.vars='id', measure=patterns("a_", "b_"), value.name=c("a_", "b_")) 

results in data table:

   id variable a_ b_ 1:  1        1  1  7 2:  2        1  2  8 3:  3        1  3  9 4:  1        2  4 10 5:  2        2  5 11 6:  3        2  6 12 

this "shape" want, variables a_3, a_4, b_3 , b_4 have been indexed 1 , 2. want variable column contain 3,3,3,4,4,4, according suffixes of variable names.

i "old-fashioned" way melt, strsplit, dcast, that's kind of cumbersome. i'm hoping one-line solution that's still fast.

we can splitstackshape. gives '.time_1' column automatically

library(splitstackshape) merged.stack(dt, var.stubs=c("a", "b"), sep="_") #   id .time_1  b #1:  1       3 1  7 #2:  1       4 4 10 #3:  2       3 2  8 #4:  2       4 5 11 #5:  3       3 3  9 #6:  3       4 6 12 

Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -