基于R中列(向量)中的上一个值编写if语句
我目前正在将一个模型从Excel转换为R,但在尝试编写部分基于同一列中先前值的IF语句时遇到了问题。以我有限的R知识和搜索过的SO网站,我找不到任何类似问题的工作从以前的例子 该模型正在跟踪一个温度剖面图,其中突出了显著的事件。每次温度升高或降低时,事件模型都会相应地返回1或0。我以前通过在R中子集复制了这些类型的模型,而不是像在excel中那样嵌套IF语句,因为excel工作得很好。但我现在有两个问题:基于R中列(向量)中的上一个值编写if语句,r,R,我目前正在将一个模型从Excel转换为R,但在尝试编写部分基于同一列中先前值的IF语句时遇到了问题。以我有限的R知识和搜索过的SO网站,我找不到任何类似问题的工作从以前的例子 该模型正在跟踪一个温度剖面图,其中突出了显著的事件。每次温度升高或降低时,事件模型都会相应地返回1或0。我以前通过在R中子集复制了这些类型的模型,而不是像在excel中那样嵌套IF语句,因为excel工作得很好。但我现在有两个问题: 第一个值适用于不同的公式并初始化模型(请参见excel屏幕的图像)。excel中的公式是-
rad_temp
读数是,我发现下面的代码正确地回答了问题。我最终使用了一个带有嵌套ifelse语句的for循环。我知道R最适合的不是FP,但它很好地复制了我的excel功能
so_example$event_formula <- NA
for (i in 1:nrow(so_example)){
ifelse(i==1,
ifelse(so_example[[i,"rad_temp"]]>25, x <- 1, x <- 0),
ifelse((so_example[[i,"cooling"]]-so_example[[i-1,"cooling"]])==1, x <- 0,
ifelse((so_example[[i,"warming"]]-so_example[[i-1,"warming"]])==1, x <- 1,
ifelse((so_example[[i,"cooling"]]-so_example[[i-1,"cooling"]])==0, x <- (so_example[[i-1,"event_formula"]]),"FALSE"
))))
so_example[[i,"event_formula"]] <- x
}
so\u示例$event\u公式25,x使用例如dplyr::lag
或data.table::shift
访问列的上一个值。另外,您对示例数据的预期结果是什么?据我所知,我不能使用lag,因为我指的是我正在编写的同一列中的最后一个值。好的,我们期待的结果,我会在上面的问题上加上。似乎你可以用一种你不必这样做的方式重构这个问题。但是,如果您不这样做,您可以通过循环索引值(比如i
)并使用so\u示例$event\u公式[i-1]
)引用前面的值来实现类似Excel的行为。我认为重构问题可能是最好的方法。对于这样的循环,如果有很多行,速度可能会非常慢,因此最好保持向量化。
# Event model
so_example$event_formula <- 0
# Rule 1
so_example$event_formula[so_example$cooling-so_example$cooling_minus1==1] <- 0
# Rule 2
so_example$event_formula[so_example$warming-so_example$warming_minus1==1] <- 1
# Rule 3
so_example$event_formula[so_example$cooling-so_example$cooling_minus1==0] <- #ref to same as previous value
# Rule 3
so_example$event_formula[(so_example$cooling-so_example$cooling_minus1==0) & (so_example$warming-so_example$warming_minus1==1) & (so_example$cooling-so_example$cooling_minus1==0)] <- #ref to same as previous value
so_example$expected_result <- c(0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1)
so_example$event_formula <- NA
for (i in 1:nrow(so_example)){
ifelse(i==1,
ifelse(so_example[[i,"rad_temp"]]>25, x <- 1, x <- 0),
ifelse((so_example[[i,"cooling"]]-so_example[[i-1,"cooling"]])==1, x <- 0,
ifelse((so_example[[i,"warming"]]-so_example[[i-1,"warming"]])==1, x <- 1,
ifelse((so_example[[i,"cooling"]]-so_example[[i-1,"cooling"]])==0, x <- (so_example[[i-1,"event_formula"]]),"FALSE"
))))
so_example[[i,"event_formula"]] <- x
}