滚动应用累计数字并遍历各列

时间:2018-08-06 04:26:34

标签: cumsum rollapply

我在数据框中有多个列,我想计算2天的累计总和。

#data frame with 3 columns a,b,c
df <- c(a = c(1,2,3,4), b = c(1,2,3,4), d = c(1,2,3,4))

#create function to calculate 2-day cumulative sum based on rollapply
cumsum2d <- function(data,colname='a') {
   data <- data %>% mutate(cumsum2d = rollapply(colname, 
                                               width = 2, 
                                               FUN = sum,
                                               align = 'right',
                                               fill = NA,
                                               na.rm = T) )
}

#loop through 3 columns and change name
colnames <- list('a','b','d')
for (colname in colnames) {
  df$newcol <- cumsum2d(data = df, colname = colname)
  names(df)[names(df == 'newcol'] <- paste0(colname,'cumsum2d')
}

cumsum2d函数不起作用。我怀疑参数colname不正确。希望能得到一些帮助。

0 个答案:

没有答案