We can use case_when
to compare the 'Value' with the previous 'Value' (lag
) and create the column 'Decision' based on whether it is lower or higher
library(dplyr)
df1 %>%
mutate(Decision = case_when(Value < lag(Value) ~ "LOW",
Value > lag(Value) ~ "HIGH", Value == lag(Value) ~ "EQUAL"))
# Value Decision
#1 1.0 <NA>
#2 2.0 HIGH
#3 1.5 LOW
#4 1.4 LOW
#5 1.4 EQUAL
Or another option is to take the difference and then change the label
s in factor
with(df1, c(NA_character_,
as.character(factor(sign(Value[-length(Value)] - Value[-1]),
levels = c(-1, 1, 0), labels = c("HIGH", "LOW", "EQUAL")))))
#[1] NA "HIGH" "LOW" "LOW" "EQUAL"
Or using a for
loop
df1$Decision <- rep(NA_character_, nrow(df1))
for(i in 2: nrow(df1)){
if(df1$Value[i] > df1$Value[i-1]){
df1$Decision[i] <- "HIGH"
} else if(df1$Value[i] < df1$Value[i-1]) {
df1$Decision[i] <- "LOW"
} else df1$Decision[i] <- "EQUAL"
}
If it needs to be a function
f1 <- function(dat, colNm, newCol) {
dat[[newCol]] <- rep(NA_character_, nrow(dat))
for(i in 2: nrow(dat)){
if(dat[[colNm]][i] > dat[[colNm]][i-1]){
dat[[newCol]][i] <- "HIGH"
} else if(dat[[colNm]][i] < dat[[colNm]][i-1]) {
dat[[newCol]][i] <- "LOW"
} else dat[[newCol]][i] <- "EQUAL"
}
dat
}
f1(df1, "Value", "Decision")
data
df1 <- structure(list(Value = c(1, 2, 1.5, 1.4, 1.4)), class = "data.frame",
row.names = c(NA,
-5L))