如何将日期行与小时列合并

时间:2018-07-09 10:36:51

标签: r dplyr

我一直在寻找答案,但我真的不知道该如何措辞!

我有一个包含ID列,类型列,单个日期列和每小时24列的数据集。

Hello <- matrix(c(c(1, 1, 1, 1, 1, 1), 
              c("a", "b", "c", "a", "b", "c"),
              c("Monday", "Monday", "Monday", "Tuesday", "Tuesday", "Tuesday"),
              c(0.0, 0.1, 0.2, 0.3, 0.4, 0.5), 
              c(0.6, 0.7, 0.8, 0.9, 1.0, 1.1)), 
             ncol = 5, 
             nrow = 6)

colnames(Hello) <- c("ID", "Type", "Day", "Morning", "Afternoon")

Hello <- as.data.frame(Hello)

我想要做的是结合日期和时间变量。看起来像这样:

Hello2.0 <- matrix(c(c(1, 1, 1), 
                 c("a", "b", "c"), 
                 c(0.0, 0.1, 0.2),
                 c(0.6, 0.7, 0.8), 
                 c(0.3, 0.4, 0.5),
                 c(0.9, 1.0, 1.1)), 
               ncol = 6,
               nrow = 3)

colnames(Hello2.0) <- c("ID", "Type", "MondayMorning", "MondayAfternoon", "TuesdayMorning", "TuesdayAfternoon")

Hello2.0 <- as.data.frame(Hello2.0)

这似乎很简单,但我无法弄清楚。预先感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

包中,您可以按以下方式使用gatherunitespread

library(tidyr)
Hello %>% 
  gather(key, value, Morning:Afternoon) %>% 
  unite(col = "daytime", Day, key, sep = "") %>% 
  spread(daytime, value)
#  ID Type MondayAfternoon MondayMorning TuesdayAfternoon TuesdayMorning
#1  1    a             0.6             0              0.9            0.3
#2  1    b             0.7           0.1                1            0.4
#3  1    c             0.8           0.2              1.1            0.5

答案 1 :(得分:1)

您可以在底数R中使用reshape()

reshape(Hello, idvar = c("Type", "ID"), timevar="Day", direction="wide")
# ID Type Morning.Monday Afternoon.Monday Morning.Tuesday Afternoon.Tuesday
# 1  1    a              0              0.6             0.3               0.9
# 2  1    b            0.1              0.7             0.4                 1
# 3  1    c            0.2              0.8             0.5               1.1