Home > Back-end >  How to convert duplicate rows to header columns in R
How to convert duplicate rows to header columns in R

Time:07-15

I would like to convert my duplicate rows in header columns following the example bellow:

File:

 A             B
Barcode        XYZ
Instrument     QS
Date           23/01/2022 
Barcode        XTRR
Instrument     QS
Date           23/01/2022
Barcode        MKLL
Instrument     QS
Date           23/01/2022  

Output:

Barcode   Instrument   Date
XYZ        QS          23/01/2022
XTRR       QS          23/01/2022
MKLL       QS          23/01/2022

Please, Does someone could help me to solve it?

CodePudding user response:

A<-c("Barcode","Instrument","Date","Barcode","Instrument","Date","Barcode","Instrument","Date")
B<-c("XYZ","QS","23/01/2022","XTRR","QS","23/01/2022","MKLL","QS","23/01/2022")
df<-data.frame(A,B)
df$id=c(rep(1,3),rep(2,3),rep(3,3))
res<-reshape(df,timevar="A",direction="wide")
names(res)<-gsub("B\\.","",names(res))
res$id<-NULL

CodePudding user response:

do.call(rbind, lapply(seq(1,nrow(d),3), \(x) {
  data.frame(Barcode =  d$B[x], Instrument=d$B[x 1], Date=d$B[x 2])
}))

Output:

  Barcode Instrument       Date
1     XYZ         QS 23/01/2022
2    XTRR         QS 23/01/2022
3    MKLL         QS 23/01/2022

Input:

d = structure(list(A = c("Barcode", "Instrument", "Date", "Barcode", 
"Instrument", "Date", "Barcode", "Instrument", "Date"), B = c("XYZ", 
"QS", "23/01/2022", "XTRR", "QS", "23/01/2022", "MKLL", "QS", 
"23/01/2022")), row.names = c(NA, -9L), class = "data.frame")
  •  Tags:  
  • r
  • Related