0

I have this small 2-row dataset

df=structure(list(V2 = c("Primera", "Segunda"), Lote = c("EN1195", 
"EN1195"), V7 = c("No registra", "No registra"), fecha_app = structure(c(18690, 
18711), class = "Date")), class = "data.frame", row.names = c(NA, 
-2L))

this I need to widen it so the second row becomes part of the first row.

df=structure(list(Lote.1 = "EN1195", V7.1 = "No registra", fecha_app.1 = structure(18690, class = "Date"), Lote.2 = "EN1195", V7.2 = "No registra", 
                  fecha_app.2 = structure(18711, class = "Date")), row.names = c(NA, -1L), class = c("tbl_df", "tbl", "data.frame"))

I have researched this but im unsure on how to implement it on my case

Andres Mora
  • 1,040
  • 8
  • 16

1 Answers1

0

You can use rowid from data.table to create a unique id and use pivot_wider.

library(dplyr)
library(tidyr)

df %>%
  mutate(id = data.table::rowid(Lote)) %>%
  pivot_wider(names_from = id, values_from = V2:fecha_app)

#  V2_1    V2_2    Lote_1 Lote_2 V7_1        V7_2        fecha_app_1 fecha_app_2
#  <chr>   <chr>   <chr>  <chr>  <chr>       <chr>       <date>      <date>     
#1 Primera Segunda EN1195 EN1195 No registra No registra 2021-03-04  2021-03-25 

Or using only data.table.

library(data.table)
setDT(df)
dcast(df, Lote~rowid(Lote), value.var = c('V2', 'V7', 'Lote', 'fecha_app'))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213