0

Hi everyone im trying to obtain this:

Problem

I'm using R to simulate a Markov Chain and the State 4 is an absorbing state, I need that once the client has entered into the state 4 the client has to remain in that state the rest of the time.

Thanks for your time

  • Hi. try to give an actual example of your data instead of the picture of your data. It will save time for those who want to answer or help. https://stackoverflow.com/help/mcve – denis Feb 27 '18 at 17:54
  • Depending on what you want this might work: `ave(dat$value, dat$Id, FUN = function(x) ifelse(cumsum(x==4)>=1, 4, x))`. You can then assign it to a new variable. A little more clarification on the question would be helpful though – Mike H. Feb 27 '18 at 18:19

2 Answers2

2

A twist on @erocoar's solution as I think it might not be what OP need:

dat$new_value <- unlist(tapply(dat$value, dat$Id, function(x) ifelse(cumsum(x==4) >0,4,x)))

modified example:

dat = data.frame(Id = rep(c("A", "B"), c(4, 3)),
                 value = c(1, 5, 4, 1, 1, 4, 1))

dat$new_value <- unlist(tapply(dat$value, dat$Id, function(x) ifelse(cumsum(x==4) >0,4,x)))

# dat
#   Id value new_value
# 1  A     1         1
# 2  A     5         5
# 3  A     4         4
# 4  A     1         4
# 5  B     1         1
# 6  B     4         4
# 7  B     1         4
moodymudskipper
  • 46,417
  • 11
  • 121
  • 167
1

You could consider using cummax (thanks to @Moody_Mudskipper for pointing this out) E.g.,

dat = data.frame(Id = rep(c("A", "B"), c(4, 3)),
                 value = c(1, 1, 4, 1, 4, 1, 1))

dat$value <- unlist(tapply(dat$value, dat$Id, cummax))

  Id value
1  A     1
2  A     1
3  A     4
4  A     4
5  B     4
6  B     4
7  B     4
erocoar
  • 5,723
  • 3
  • 23
  • 45