Home > Software design >  Reorganizing column data
Reorganizing column data

Time:11-12

I have the following data:

structure(list(DATA = c("01/01/2020", "02/01/2020", "03/01/2020"
), HORA = c("01:19", "02:09", "03:17"), ALT = c(0.7, 0.8, 0.9
), HORA.1 = c("07:53", "08:51", "10:02"), ALT.1 = c(1.8, 1.8, 
1.7), HORA.2 = c("13:41", "14:47", "16:08"), ALT.2 = c(0.8, 0.9, 
0.9), HORA.3 = c("20:08", "21:08", "22:17"), ALT.3 = c(1.9, 1.8, 
1.8)), class = "data.frame", row.names = c(NA, -3L))

enter image description here

I would to get this form of data:

enter image description here

Thank's all

CodePudding user response:

We can use pivot_longer - use names_pattern to capture the pattern till the . (if any) and other characters (.*) that follows

library(tidyr)
 pivot_longer(df1, cols = -DATA, names_to = c(".value"),
     names_pattern = "^([^.] )\\.?.*")

-output

# A tibble: 12 × 3
   DATA       HORA    ALT
   <chr>      <chr> <dbl>
 1 01/01/2020 01:19   0.7
 2 01/01/2020 07:53   1.8
 3 01/01/2020 13:41   0.8
 4 01/01/2020 20:08   1.9
 5 02/01/2020 02:09   0.8
 6 02/01/2020 08:51   1.8
 7 02/01/2020 14:47   0.9
 8 02/01/2020 21:08   1.8
 9 03/01/2020 03:17   0.9
10 03/01/2020 10:02   1.7
11 03/01/2020 16:08   0.9
12 03/01/2020 22:17   1.8

Or with data.table

library(data.table)
melt(setDT(df1), measure = patterns("^HORA", "^ALT"), 
    value.name = c("HORA", "ALT"))
  • Related