R:为每个提取日期生成值行

时间:2017-12-11 17:25:37

标签: r date dplyr data.table extract

我有一个这样的数据框:

ID   Year   Week  Monday  Tuesday  Wednesday
12   2017    42     8         9         8,5
12   2017    43     9         11        7,3
13   2017    43     9         10        6,8

我想改变它以实现这个目标:

ID   day          time
12   16/10/2017   8
12   17/10/2017   9
12   18/10/2017   8,5
12   23/10/2017   9
12   24/10/2017   11
12   25/10/2017   7,3
12   23/10/2017   9
12   24/10/2017   10
12   25/10/2017   6,8

有什么想法吗?我尝试使用dplyr,但仍然没有找到解决方案

1 个答案:

答案 0 :(得分:1)

希望这有帮助!

library(dplyr)
library(tidyr)

df %>% 
  gather(day, time, Monday:Wednesday) %>%
  mutate(date = as.Date(paste(Year, Week, day),"%Y %U %A")) %>%
  arrange(ID, Year, Week) %>%
  select(-Year, -Week, -day)

#  ID time       date
#1 12    8 2017-10-16
#2 12    9 2017-10-17
#3 12  8,5 2017-10-18
#4 12    9 2017-10-23
#5 12   11 2017-10-24
#6 12  7,3 2017-10-25
#7 13    9 2017-10-23
#8 13   10 2017-10-24
#9 13  6,8 2017-10-25


#sample data
> dput(df)
structure(list(ID = c(12L, 12L, 13L), Year = c(2017L, 2017L, 
2017L), Week = c(42L, 43L, 43L), Monday = c(8L, 9L, 9L), Tuesday = c(9L, 
11L, 10L), Wednesday = structure(c(3L, 2L, 1L), .Label = c("6,8", 
"7,3", "8,5"), class = "factor")), .Names = c("ID", "Year", "Week", 
"Monday", "Tuesday", "Wednesday"), class = "data.frame", row.names = c(NA, 
-3L))