Demetri Pananos
Demetri Pananos

Reputation: 7404

Mutate rows of dataframe based on previous rows

I have three vectors, coin.flips, alpha, and beta. Here they are initialized:

coin.flips <- c(NA,rbinom(n = 5, size = 1, prob = 0.5))

N <- length(coin.flips)

alpha <- rep(0,length(coin.flips))
alpha[1]<-1

beta <- rep(0,length(coin.flips))
beta[1]<-1

I would like to update alpha/beta depending on the value of coin.flips. If coin.flips==1 then increment alpha, else increment beta. Here is how I do it in base R.

for(i in 2:N){
  if(coin.flips[i]>0){
    alpha[i] = alpha[i-1]+1
    beta[i] = beta[i-1]
  }
  else{
    alpha[i] = alpha[i-1]
    beta[i] = beta[i-1]+1
  }
}

How can I do this in a tidy way? Suppose that coin.flips is a column of a tibble or data.frame. Is there an easy way to construct new columns alpha/beta that increment depending on the value of coin.flips and the previous values of alpha/beta?

Upvotes: 0

Views: 321

Answers (1)

davsjob
davsjob

Reputation: 1960

Here's my take. Given you have a column called coin.flips in dataframe df:

library(dplyr)
df <- data.frame(coin.flips = c(rbinom(n = N, size = 1, prob = 0.5)))

df <- df %>% 
  mutate(alpha = 1 + cumsum(coin.flips),
         beta  = 1 + cumsum(if_else(coin.flips == 0, 1, 0))) %>% 
  print

Upvotes: 1

Related Questions