我在数据框中有多个列,我想计算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
不正确。希望能得到一些帮助。