如果值达到某个阈值,则下一个不能低于
if value reach certain threshold the next one can't go under
大家好,我正在尝试获取此信息:
Problem
我正在使用 R 来模拟马尔可夫链,状态 4 是一种吸收状态,我需要一旦客户端进入状态 4,客户端必须在其余时间保持该状态。
感谢您的宝贵时间
您可以考虑使用 cummax
(感谢@Moody_Mudskipper 指出这一点)例如,
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 解决方案的一个转折点,因为我认为这可能不是 OP 所需要的:
dat$new_value <- unlist(tapply(dat$value, dat$Id, function(x) ifelse(cumsum(x==4) >0,4,x)))
修改示例:
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
大家好,我正在尝试获取此信息:
Problem
我正在使用 R 来模拟马尔可夫链,状态 4 是一种吸收状态,我需要一旦客户端进入状态 4,客户端必须在其余时间保持该状态。
感谢您的宝贵时间
您可以考虑使用 cummax
(感谢@Moody_Mudskipper 指出这一点)例如,
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 解决方案的一个转折点,因为我认为这可能不是 OP 所需要的:
dat$new_value <- unlist(tapply(dat$value, dat$Id, function(x) ifelse(cumsum(x==4) >0,4,x)))
修改示例:
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