简体   繁体   中英

How to combine date rows with hour columns

I have been looking for an answer but I don't really know how to word this question!

I have a data set with an ID column, a type column, a single date column and 24 columns for each hour.

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)

What I want to do is to combine the dates and the time variable. So it looks like:

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)

It seems so simple, but I just cannot figure it out. Thanks in advance for any help!

From the package you can use gather , unite and spread as follows

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

You could use reshape() in base R.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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