Изготовление колонн с тидиром


У меня есть такой набор данных:

            test          value
1             no 091/A/NBP/2018
2  effectiveDate     2018-05-11
3            mid         3.5708
4             no 092/A/NBP/2018
5  effectiveDate     2018-05-14
6            mid         3.5558
7             no 093/A/NBP/2018
8  effectiveDate     2018-05-15
9            mid         3.5931
10            no 094/A/NBP/2018
11 effectiveDate     2018-05-16
12           mid         3.6241
13            no 095/A/NBP/2018
14 effectiveDate     2018-05-17
15           mid         3.6283
16            no 096/A/NBP/2018
17 effectiveDate     2018-05-18
18           mid         3.6385

Какую команду следует использовать для создания фрейма данных, в котором столбцы no, mid и effectiveDate являются столбцами?

1 2

1 ответ:

Надеюсь, это поможет!

library(dplyr)
library(tidyr)

df %>%
  mutate(row_id = rep(1:(n()/3), each=3)) %>%
  spread(test, value) %>%
  select(-row_id)

Вывод:

  effectiveDate    mid             no
1    2018-05-11 3.5708 091/A/NBP/2018
2    2018-05-14 3.5558 092/A/NBP/2018
3    2018-05-15 3.5931 093/A/NBP/2018
4    2018-05-16 3.6241 094/A/NBP/2018
5    2018-05-17 3.6283 095/A/NBP/2018
6    2018-05-18 3.6385 096/A/NBP/2018

Примерные данные:

df <- structure(list(test = c("no", "effectiveDate", "mid", "no", "effectiveDate", 
"mid", "no", "effectiveDate", "mid", "no", "effectiveDate", "mid", 
"no", "effectiveDate", "mid", "no", "effectiveDate", "mid"), 
    value = c("091/A/NBP/2018", "2018-05-11", "3.5708", "092/A/NBP/2018", 
    "2018-05-14", "3.5558", "093/A/NBP/2018", "2018-05-15", "3.5931", 
    "094/A/NBP/2018", "2018-05-16", "3.6241", "095/A/NBP/2018", 
    "2018-05-17", "3.6283", "096/A/NBP/2018", "2018-05-18", "3.6385"
    )), class = "data.frame", row.names = c("1", "2", "3", "4", 
"5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", 
"16", "17", "18"))