简体   繁体   English

将列扩展为R中的日期

[英]Expand columns into dates in R

I have data structured in the following way: 我的数据结构如下:

  • date H01 H02 ... H48 日期H01 H02 ... H48

  • 01-Jan-19 15,328 15,273 ... 5,241 19年1月1日15,328 15,273 ... 5,241

  • 02-Jan-19 17,412 17,474 ... 7,625 19年1月2日17,412 17,474 ... 7,625

H01 to H48 represent values each 30 min within the same day. H01至H48表示同一天内每30分钟的值。 This does not follow the principles of tidy data. 这不遵循整洁数据的原则。

I would like to have only two columns: 我只希望有两列:

  • date value 日期值
  • 01/01/2019 00:00 15,328 01/01/2019 00:00 15,328
  • 01/01/2019 00:30 15,273 01/01/2019 00:30 15,273
  • 01/01/2019 01:00 ... 01/01/2019 01:00 ...

How can I obtain this in R? 我如何在R中获得它?

Thank you! 谢谢!

The package tidyr makes this pretty easy with the gather function. 该软件包tidyr使得这很容易与gather功能。

library(dplyr)
library(tidyr)

df <- tibble(Date = c("01-Jan-19", "02-Jan-19"),
             H01 = c(15328, 17412),
             H02 = c(15273, 17474))

times.df <- tibble(Code = c("H01", "H02"),
                       Time = c("00:30", "1:00"))

gather(df, key = "Code", value = "Value", -Date) %>%
  left_join(times.df) %>%
  mutate(DateTime = dmy_hm(paste(Date, Time, sep = " "))) 

# Joining, by = "Code"
# # A tibble: 4 x 5
# Date      Code  Value Time  DateTime           
# <chr>     <chr> <dbl> <chr> <dttm>             
#   1 01-Jan-19 H01   15328 00:30 2019-01-01 00:30:00
# 2 02-Jan-19 H01   17412 00:30 2019-01-02 00:30:00
# 3 01-Jan-19 H02   15273 1:00  2019-01-01 01:00:00
# 4 02-Jan-19 H02   17474 1:00  2019-01-02 01:00:00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM