如何计算每日百分比变化和三天百分比变化R?

如何计算每日百分比变化和三天百分比变化R?,r,R,我有一个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"),

我有一个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))
ads您可以尝试:

df %>% 
  mutate_at(.vars = vars(dplyr::matches("(likes)|(comments)")), 
            funs(daily_change = ./lag(.)*100,
                 three_day_change = ./lag(., 3)*100))
同样,如果不需要ad和date变量:

df %>% 
  select(likes, comments) %>% 
  mutate_all(funs(daily_change = ./lag(.)*100,
                 three_day_change = ./lag(., 3)*100))
或者,如果您需要:

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)
此外,您还可以通过对原始代码进行少量修改来获得相同的结果:

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))
daily\u pct
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))