[英]How to calculate daily percent change and three day percent change R?
I have a datframe with that I want to calculate the percent change day by day and also over three days but when I do it the results don't really seem right. 我有一个datframe,我想每天甚至在三天内计算百分比变化,但是当我这样做时,结果似乎并不正确。
ads <- data.frame(ad = c(ad1, ad1, ad1, ad1, ad2, ad2, ad2, ad3, ad3, ad3),
date = c("11-10", "11-11", "11-12", "11-13", "11-10", "11-11", "11-12", "11-10", "11-11", "11-12"),
likes = c(20, 30, 18, 5, 34, 68, 55, 44, 33, 20),
comments = c(21, 22, 10, 1, 10, 43, 24, 34, 21, 11))
so for I have this: 所以我有这个:
daily_pct <- function(x) x/lag(x)
three_pct <- function(x) x/lag(x ,k = 3)
daily_pct_change <- ads %>%
mutate_each(funs(daily_pct), c(likes,comments))
three_pct_change <- ads %>%
mutate_each(funs(three_pct), c(likes, comments))
Am I doing this correctly? 我这样做正确吗? I can't figure out how to get the three day one to work either. 我也不知道如何让三天一班的工作。 Thanks! 谢谢!
You can try: 你可以试试:
df %>%
mutate_at(.vars = vars(dplyr::matches("(likes)|(comments)")),
funs(daily_change = ./lag(.)*100,
three_day_change = ./lag(., 3)*100))
Similarly, if you do not need the ad and date variables: 同样,如果您不需要ad和date变量:
df %>%
select(likes, comments) %>%
mutate_all(funs(daily_change = ./lag(.)*100,
three_day_change = ./lag(., 3)*100))
Or if you need them: 或者,如果您需要它们:
df %>%
select(likes, comments) %>%
mutate_all(funs(daily_change = ./lag(.)*100,
three_day_change = ./lag(., 3)*100)) %>%
rowid_to_column() %>%
left_join(df %>% rowid_to_column() %>% select(rowid, ad, date), by = c("rowid" = "rowid")) %>%
select(-rowid)
Also, you can get the same results by a small modification of your original code: 另外,您可以通过对原始代码进行少量修改来获得相同的结果:
daily_pct <- function(x) x/lag(x)*100
three_pct <- function(x) x/lag(x, 3)*100
df %>%
mutate_at(.vars = vars(dplyr::matches("(likes)|(comments)")),
funs(daily_change = daily_pct,
three_day_change = three_pct))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.