Guest User

Untitled

a guest
Jan 15th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. date <- seq(as.Date("2012-09-01"), Sys.Date(), 1)
  2. id <- rep(c("a","b","c","d"), 8)
  3. bdate <- seq(as.Date("2012-08-01"), as.Date("2012-11-01"), 1)[sample(1:32, 32)]
  4.  
  5. # The end date should be random but greater than the begin date. However, I set it to 15 days later for simplicity.
  6. edate <- bdate + 15
  7.  
  8. value <- seq(1, 1000, 1)[sample(1:1000, 32)]
  9. dfa <- data.frame(id, value, bdate, edate)
  10. names(dfa) <- c("ID", "Value", "Begin.Date", "End.Date")
  11.  
  12. Date a b c
  13. 2012-08-01 XXX YYY ZZZ
  14. 2012-08-02 XXX YYY ZZZ
  15. 2012-08-03 XXX YYY ZZZ
  16.  
  17. # Create additional data frame
  18. dfb <- data.frame(seq(as.Date("2012-08-01"), as.Date("2012-11-01"), 1))
  19. names(dfb)[1] <- "Date"
  20.  
  21. # Variable for unique IDs
  22. nid <- unique(dfa$ID)
  23.  
  24. # Number of total IDs
  25. tid <- length(nid)
  26.  
  27. for (i in c(1:tid))
  28. {
  29. sums <- vapply(dfb$Date, function(x)
  30. {
  31. temp <- subset(dfa, dfa$ID == nid[i])
  32. temp <- subset(temp, temp$Begin.Date < x & temp$End.Date > x)
  33. res <- sum(temp$Value)
  34. res
  35. }, FUN.VALUE = 0.1
  36. )
  37. dfb[1+i] <- sums
  38. }
  39.  
  40. # Change column names to ID
  41. names(dfb) <- c("Date", as.character(nid))
  42.  
  43. mydate <- as.Date("2012-08-25") # take Aug 25, 2012 as an example
  44. ind <- (dfa$Begin.Date <= mydate) & (dfa$End.Date >= mydate)
  45. temp <- subset(dfa, ind)
  46. out <- table(temp$ID)
  47.  
  48. library("plyr")
  49. library("reshape2")
  50.  
  51. earliest.date <- as.Date("2007-01-01")
  52. latest.date <- as.Date("2012-11-01")
  53.  
  54. dfa.long <- adply(dfa, 1, function(DF) {
  55. if(DF$End.Date >= earliest.date & DF$Begin.Date <= latest.date) {
  56. data.frame(Date=seq(max(DF$Begin.Date, earliest.date),
  57. min(DF$End.Date, latest.date),
  58. 1))
  59. }
  60. })
  61.  
  62. dfb <- ddply(dfa.long, .(Date, ID), summarise, sum=sum(Value))
  63. dfb <- dcast(dfb, Date~ID, value.var="sum", fill=0)
Add Comment
Please, Sign In to add comment