0

I'm trying to learn how to use apply, but am getting a bit stuck. This loop is converting all of the columns (except the first four) to their accumulated sums.

Can anyone help me? Thanks!

for (i in seq_along(newbuilds.byfuel.bydate)) {
  if (i >= 5) {
    newbuilds.byfuel.bydate[i] <- cumsum(newbuilds.byfuel.bydate[i])

  }
}
  • 1
    Is `newbuilds.byfuel.bydate` a data.frame? Make sure to provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) when asking for help. That will make it easier to help you. – MrFlick Apr 03 '17 at 15:24

1 Answers1

2

This is how I would do this if your object is a data.frame:

## dummy dataset
x <- mtcars

Use lapply to loop over the desired columns, calculate the cumsum, and then overwrite the original columns:

x[5:ncol(x)] <- lapply(x[5:ncol(x)], cumsum)

Alternatively, loop over the un-dropped columns:

x[-(1:4)] <- lapply(x[-(1:4)], cumsum)
Zelazny7
  • 39,946
  • 18
  • 70
  • 84