【问题标题】:Making columns with tidyR使用 tidyR 制作列
【发布时间】:2018-05-18 18:14:08
【问题描述】:

我有一个这样的数据集:

            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 为列的数据框?

【问题讨论】:

  • spread(test, value)

标签: r dplyr tidyr


【解决方案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"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-26
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    相关资源
    最近更新 更多