Guest User

Untitled

a guest
Jan 18th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. # Example dataset
  2. Data <- data.frame(
  3. ID = sample(c("A", "B", "C", "D"), 50, replace = TRUE),
  4. Act = sample(c("eat", "sleep", "play"), 50, replace = TRUE),
  5. Period = sample(c("pre", "post"), 50, replace = TRUE)
  6. )
  7.  
  8. # Separate my data by period
  9. DataPre <- as.data.frame(Data[ which(Data $Period == "pre"), ])
  10. DataPost <- as.data.frame(Data[ which(Data $Period == "post"), ])
  11.  
  12. # Get the minimum # observations for each ID across both periods
  13. Num <- Data %>%
  14. group_by(ID, Period) %>%
  15. summarise(number=n()) %>%
  16. group_by(ID) %>%
  17. summarise(min=min(number))
  18.  
  19. # Function to get the mean proportion per ID
  20. meanAct <- function(x){
  21. x %>%
  22. group_by(ID, Act) %>%
  23. summarise (n = n()) %>%
  24. mutate(freq = n / sum(n))
  25. }
  26.  
  27. # See "8888" Here I want to subsample the Num$Min for each ID
  28. DataResults <- function(x, rep){
  29. reps <- replicate(rep, meanAct(x[sample(1:nrow(x), 8888, replace=FALSE),]))
  30. meanfreq <- apply(simplify2array(reps[3, 1:2]), 1, mean)
  31. sd <- apply(simplify2array(reps[3, 1:2]), 1, sd)
  32. lower <- meanfreq - 1.96*(sd/sqrt(8888))
  33. upper <- meanfreq + 1.96*(sd/sqrt(8888))
  34. meanAct <- as.vector(reps[[1]])
  35. output <- data.frame(meanAct, meanfreq, sd, lower, upper)
  36. print(output)
  37. }
  38.  
  39. # Print results
  40. DataResults(DataPre, 1000)
  41. DataResults(DataPost, 1000)
  42.  
  43. # Somehow I get the mean for the population by averaging across all IDs
  44. DataMeanGroup <- DataMean %>%
  45. group_by(Period) %>%
  46. summarise (mean = mean(prop))
Add Comment
Please, Sign In to add comment