You can do this in one line with:
cumsum(ifelse(is.na(x), 0, x)) + x*0
# a b c d e f g h
# 1 3 3 NA 7 NA NA 13
Or, similarly:
library(dplyr)
cumsum(coalesce(x, 0)) + x*0
# a b c d e f g h
# 1 3 3 NA 7 NA NA 13
More Related Contents:
- How can I find compound words, removing spaces between them and replace them in my corpus?
- Faster ways to calculate frequencies and cast from long to wide
- How can I remove all duplicates so that NONE are left in a data frame?
- strptime, as.POSIXct and as.Date return unexpected NA
- How to delete a row by reference in data.table?
- How to replace NA with mean by group / subset?
- Measuring function execution time in R
- R – Concatenate two dataframes?
- Error in plot.new() : figure margins too large in R
- Generate a repeating sequence based on vector
- anova test fails on lme fits created with pasted formula
- How can we make xkcd style graphs?
- lib unspecified & Error in loadNamespace
- First entry from string split
- Replace values in a vector based on another vector
- Sort a data.table fast by Ascending/Descending order
- Join R data.tables where key values are not exactly equal–combine rows with closest times
- Reasons that ggplot2 legend does not appear [duplicate]
- How to convert integer into categorical data in R?
- set ggplot plots to have same x-axis width and same space between dot plot rows
- lapply-ing with the “$” function
- How to change the first row to be the header in R?
- Insert a logo in upper right corner of R markdown pdf document
- How to replace NA (missing values) in a data frame with neighbouring values
- Add row in each group using dplyr and add_row()
- list of masked functions in R
- Using R convert data.frame to simple vector
- R programming: cache the inverse of a matrix
- Multiply columns in a data frame by a vector
- R – What algorithm does geom_density() use and how to extract points/equation of curves?