SHARE
TWEET

Untitled

a guest Mar 20th, 2019 52 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. df = data.frame(group = c(rep('A',4), rep('B',3)),
  2.             response = c(1,4,2,1,1,2,3),
  3.             treatment = c("control","100mg","200mg","50mg","control","100mg","200mg"))
  4.  
  5. > df
  6.     group response treatment
  7.        A     1   control
  8.        A     4     100mg
  9.        A     2     200mg
  10.        A     1      50mg
  11.        B     1   control
  12.        B     2     100mg
  13.        B     3     200mg
  14.      
  15. # function for % change
  16. pct <- function(x) {(x/lag(x)-1)*100}
  17.  
  18. library(dplyr)
  19. # group data and apply function
  20. percChange <- df %>%
  21.   group_by(group) %>%
  22.   mutate_at(vars(response), funs(pct))
  23.  
  24. # the output (perChange) is:
  25.  
  26. #   group response treatment
  27. # 1 A        NA   control  
  28. # 2 A       300   100mg    
  29. # 3 A       -50   200mg    
  30. # 4 A       -50   50mg    
  31. # 5 B        NA   control  
  32. # 6 B       100   100mg    
  33. # 7 B        50   200mg
  34.      
  35. # group  response  treatment
  36. # 1 A        NA   control  
  37. # 2 A       300   100mg    
  38. # 3 A       100   200mg    
  39. # 4 A       0     50mg    
  40. # 5 B       NA    control  
  41. # 6 B       100   100mg    
  42. # 7 B       200   200mg
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top