我有一个包含变量的小标题,这些变量使用“99”或“999”作为高于之前值的所有值的组合。我如何将其更改为 + 2 之前的值。
示例如下。
level <- c(1,2,3,4,99)
variable <- c('age', 'age','age','age','age')
value <- c(.5, .75, 1, 1.25, 1.89)
d <- data.frame(Variable = variable, Level = level, value = value)
我想最终得到
Variable Level Value
age 1 .5
age 2 .75
age 3 1
age 4 1.25
age 6 1.89
在起始值为99的情况下,我什至不知道从哪里开始选择99之前的值。
也许
d$Level <- if(d$Level = 99, nrow(-1) + 2, d$Level)
最佳答案
我会使用data.table::shift()
:
with(d, ifelse(Level %in% c(99, 999), shift(Level) + 2, Level))
[1] 1 2 3 4 6
但是要在base R
中执行此操作,您可以定义一个辅助函数:
baseShiftBy1 <- function(x) c(NA, x[-length(x)])
with(d, ifelse(Level %in% c(99, 999), baseShiftBy1(Level) + 2, Level))
关于根据之前的值替换值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53868782/