Home > Net >  Summarizing previous vector values
Summarizing previous vector values

Time:01-29

I have vector that looks like that:

 X2             X3 X4 X5 X6 X7 X8 X9 X10 X11 X12 X13 X14 X15 X16 X17 X18 X19 X20 X21 X22 X23 X24   X25
2 M. VERSTAPPEN 18 25 18 19 25  0 26  25  26   3   2  NA  25   2  18  18  25  25  20  19  18  26 395.5

I want to create new vector that contains summary of all previous scores for example:

X3 X4 X5
18 43 61

etc. I tried doing something like that but it doesnt work.

ve <- c()
for(i in 3:25){
  ve <- append(paste0("X",i 1))
  stats %>% 
    mutate(ve[i] =(stats[,i] stats[,i-1]))
}

CodePudding user response:

I am not sure if you have a dataframe or a vector. From your attempted code it looks that you are dealing with a dataframe. It is easier to help if you provide data in a reproducible format

data

stats <- structure(list(X2 = "M.VERSTAPPEN", X3 = 18L, X4 = 25L, X5 = 18L, 
    X6 = 19L, X7 = 25L, X8 = 0L, X9 = 26L, X10 = 25L, X11 = 26L, 
    X12 = 3L, X13 = 2L, X14 = NA, X15 = 25L, X16 = 2L, X17 = 18L, 
    X18 = 18L, X19 = 25L, X20 = 25L, X21 = 20L, X22 = 19L, X23 = 18L, 
    X24 = 26L, X25 = 395.5), class = "data.frame", row.names = "2")

cumsum function would be helpful.

cols <- paste0('X', 3:25)
vec <- unlist(stats[cols])
stats[cols] <- cumsum(replace(vec, is.na(vec), 0))
stats

#            X2 X3 X4 X5 X6  X7  X8  X9 X10 X11 X12 X13 X14 X15 X16 X17
#2 M.VERSTAPPEN 18 43 61 80 105 105 131 156 182 185 187 187 212 214 232

#  X18 X19 X20 X21 X22 X23 X24   X25
#2 250 275 300 320 339 357 383 778.5

Since there are NA values in the data I have replaced with 0 while taking cumsum.

CodePudding user response:

Perhaps cumsum is the thing you are after

df[-1] <- t(apply(df[-1],1,cumsum))
  •  Tags:  
  • Related