用tidyR制作列

时间:2018-05-18 18:14:08

标签: r dplyr tidyr

我有这样的数据集:

            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 个答案:

答案 0 :(得分:2)

希望这有帮助!

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"))