Matt DeRusha
Matt DeRusha

Reputation: 31

converting FOR loop to apply in R

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])

  }
}

Upvotes: 0

Views: 115

Answers (1)

Zelazny7
Zelazny7

Reputation: 40628

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)

Upvotes: 2

Related Questions