2
0

state.R 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # CALCULATE PATIENT STATE ALGORITHM
  2. STATE = c("WALK", "UP", "DOWN", "SIT")
  3. size_ <- 5
  4. differ_ <- 0.1
  5. POINTS <- data.frame(
  6. index = integer(1)
  7. )
  8. POINTS["state"] <- 0
  9. POINTS["probability"] <- 0
  10. for(i in 1:size_){
  11. POINTS[LETTERS[i]] <- 0
  12. }
  13. for(i in size_:(nrow(DATA)-size_)){
  14. start <- DATA[i,]$Head.y
  15. end <- DATA[i+size_,]$Head.y
  16. state_ <- NULL
  17. if(((start - end) < differ_) && (start - end) > -differ_){
  18. if(start >= mean(DATA$Head.y)){ #WALK (4)
  19. state_ <- 1
  20. }
  21. else{ #SIT (4)
  22. state_ <- 4
  23. }
  24. }
  25. else if((start - end) < differ_) { #UP (2)
  26. state_ <- 2
  27. }
  28. else if((start - end) > differ_) { #UP (3)
  29. state_ <- 3
  30. }
  31. else {
  32. state_ <- 1
  33. }
  34. for(j in 0:size_-1){
  35. POINTS[i-j,LETTERS[j+1]] <- state_
  36. }
  37. POINTS[i,]$index <- DATA[i,]$Time
  38. if(i>size_*2 && i<=((nrow(DATA) - size_))){
  39. tmp_ <- (
  40. tbl_df(
  41. table(
  42. POINTS[i-size_,] %>%
  43. unlist(., use.names=FALSE)
  44. )
  45. ) %>%
  46. arrange(
  47. desc(n)
  48. )
  49. )
  50. POINTS[i-size_,]$state <- tmp_[1,]$Var1
  51. POINTS[i-size_,]$probability <- ((1 / size_) * tmp_[1,]$n)
  52. }
  53. DATA[i,]$state = state_
  54. }
  55. print("STATE CALCULATION DONE")
  56. remove(tmp_)
  57. DATA <- DATA[complete.cases(DATA),]
  58. rownames(DATA) <- 1:nrow(DATA)
  59. DATA$index = as.integer(rownames(DATA))
  60. WALKING <- strtoi(rownames(DATA[DATA$state==1,]))
  61. if(!consistent(WALKING)){
  62. stop("Patient not consistently walking, (Maybe he/she fell). Anyway, we can't analyse this data", call. = FALSE)
  63. }
  64. # CALCULATE STRAIGHT WALKING PATH
  65. yPrediction <-lm(Head.y ~ I(index^2)+index, data=DATA[min(WALKING):max(WALKING),])
  66. yPredicted <- as.vector(predict(yPrediction, data.frame(index=WALKING)))
  67. WALKBASE <- mean(c(yPredicted[1], tail(yPredicted, n=1)))
  68. for(i in WALKING[1]:(length(WALKING) + WALKING[1] - 1)){
  69. DATA[i,]$Head.y <- DATA[i,]$Head.y - (yPredicted[i-WALKING[1]+1] - WALKBASE)
  70. }
  71. plot(POINTS$probability, type = "l")
  72. # http://stats.stackexchange.com/questions/30975/how-to-add-non-linear-trend-line-to-a-scatter-plot-in-r
  73. # http://www.mathsisfun.com/geometry/parabola.html