简体   繁体   中英

rearrange a multiple columns dataframe

I want to rearrange my dataframe as follow: the first 3 columns have to be appended one below the other as well as the second 3. The ID and Class columns have to be kept according to the dataframe rearrangement.

Starting dataframe id df

set.seed(1)
 df <- data.frame(ID = rep(c("CT1", "CT2", "CT3", "SB1", "SB2","SB3","AM1", "AM2", "AM3")),
                     Class = rep(c("CT", "SB", "AM"), each = 3),
                     replicate(6,sample(0:100,9,rep=TRUE)))

Output is df2

set.seed(1)
    df2 <- data.frame(ID = c(rep(c("CT1", "CT2", "CT3", "SB1", "SB2","SB3","AM1", "AM2", "AM3" ), times=3)),
                            Class =  rep(rep(c("CT", "SB", "AM"), each= 3), times=3),
                            replicate(2,sample(0:100,27,rep=TRUE)))

I have tried couple of approaches utilising merge by id.vars ID and Class

We may use

data.frame(df[, c("ID", "Class")], X1 = unlist(df[, 3:5]), X2 = unlist(df[, 6:8]))
#      ID Class X1 X2
# X11 CT1    CT 26 38
# X12 CT2    CT 37 87
# X13 CT3    CT 57 34
# X14 SB1    SB 91 48
# X15 SB2    SB 20 60
# X16 SB3    SB 90 49
# ...

The first two columns get expanded by recycling, while the other two are constructed conveniently with unlist . There isn't really any need for something fancy in this case if that's your actual problem and there aren't hundreds of such triplets.

Multiple set of columns can be melt ed using data.table

library(data.table)
melt(setDT(df), measure = list(3:5, 6:8), value.name = c('X1', 'X2'))[,
                 variable := NULL][] 
#    ID Class X1 X2
#1: CT1    CT 26 38
#2: CT2    CT 37 87
#3: CT3    CT 57 34
#4: SB1    SB 91 48
#5: SB2    SB 20 60
#6: SB3    SB 90 49
# ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM