Мы можем использовать lag
из dplyr
.
library(dplyr)
df1 %>%
arrange(Year) %>%
group_by(Name) %>%
mutate(Bil = case_when(Ch1 >= lag(Ch1) ~ Ch1 / lag(Ch1),
Ch1 < lag(Ch1) ~ -lag(Ch1)/Ch1))
Данные
df1 <- structure(list(Name = structure(c(1L, 1L, 1L, 1L, 2L, 2L), .Label = c("A",
"B"), class = "factor"), Year = c(1995L, 1996L, 1997L, 2000L,
1997L, 1998L), Ch1 = structure(1:6, .Label = c("x1", "x2", "x3",
"x4", "y1", "y2"), class = "factor"), Origin = structure(c(1L,
2L, 1L, 1L, 3L, 3L), .Label = c("a", "b", "c"), class = "factor")), class = "data.frame", row.names = c(NA,
-6L))
df1<-df1 %>% mutate(Ch1 = round(runif(n=6,100,1000),2))