0

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?

obraia
  • 1
  • Does this answer your question? [Go from long to wide using tidyr's pivot\_wider](https://stackoverflow.com/questions/64940108/go-from-long-to-wide-using-tidyrs-pivot-wider) – harre Jul 14 '22 at 13:57
  • And: https://stackoverflow.com/questions/10589693/convert-data-from-long-format-to-wide-format-with-multiple-measure-columns – harre Jul 14 '22 at 13:59
  • 1
    Answer to the deleted comment: `df |> pivot_wider(names_from = "A", values_from = "B"), values_fn = list) |> unnest_longer(everything())` – harre Jul 14 '22 at 14:10
  • There are error in formula.the links that u sent me dosen´t works. – obraia Jul 14 '22 at 14:12
  • @harre response works, but there is an extra `)` embedded within the `pivot_wider()` call. Remove it, and that will work also. – langtang Jul 14 '22 at 14:32
  • Thanks @langtang. I.e. without typo: `df |> pivot_wider(names_from = "A", values_from = "B", values_fn = list) |> unnest_longer(everything())` – harre Jul 14 '22 at 14:33

2 Answers2

0
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
0
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")
langtang
  • 22,248
  • 1
  • 12
  • 27
  • object 'x' not found – obraia Jul 14 '22 at 14:20
  • 1
    It works. So does the answer provided by @harre, as long as you remove the additional `)` after "B".. That is, the `value_fn = list` should be included in the `pivot_wider` call – langtang Jul 14 '22 at 14:27