Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- df = data.frame(group = c(rep('A',4), rep('B',3)),
- response = c(1,4,2,1,1,2,3),
- treatment = c("control","100mg","200mg","50mg","control","100mg","200mg"))
- > df
- group response treatment
- A 1 control
- A 4 100mg
- A 2 200mg
- A 1 50mg
- B 1 control
- B 2 100mg
- B 3 200mg
- # function for % change
- pct <- function(x) {(x/lag(x)-1)*100}
- library(dplyr)
- # group data and apply function
- percChange <- df %>%
- group_by(group) %>%
- mutate_at(vars(response), funs(pct))
- # the output (perChange) is:
- # group response treatment
- # 1 A NA control
- # 2 A 300 100mg
- # 3 A -50 200mg
- # 4 A -50 50mg
- # 5 B NA control
- # 6 B 100 100mg
- # 7 B 50 200mg
- # group response treatment
- # 1 A NA control
- # 2 A 300 100mg
- # 3 A 100 200mg
- # 4 A 0 50mg
- # 5 B NA control
- # 6 B 100 100mg
- # 7 B 200 200mg
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement