Вот один из способов сделать это с помощью пользовательской функции.
library(dplyr)
change_to_1 <- function(From, To, Zones) {
#Get index where zone = 0
inds <- which(Zones == 0)
#Differentiate separate instances of 0's
all_0_pairs <- split(inds, cumsum(c(TRUE, diff(inds) > 1)))
#Change the Zone values to 1 where the difference is less than 1
#and 0-index is not present in first or last row.
Zones[unlist(Filter(function(i) {
if(all(between(i, 2, length(Zones) - 1)))
(From[i[length(i)] + 1] - To[i[1] - 1]) <= 1
else
FALSE
}, all_0_pairs))] <- 1
return(Zones)
}
Затем примените эту функцию к каждой группе.
df %>% group_by(Groups) %>% mutate(New_zone = change_to_1(From, To, Zones))
# Sample.ID Groups From To Zones New_zone
# <int> <fct> <dbl> <dbl> <int> <dbl>
# 1 1 GRP1 2 3 1 1
# 2 2 GRP1 3 4 1 1
# 3 3 GRP2 4 5 0 0
# 4 4 GRP2 5 6 1 1
# 5 5 GRP2 6 7 1 1
# 6 6 GRP2 7 8 0 0
# 7 7 GRP2 8 9 0 0
# 8 8 GRP2 9 10 1 1
# 9 9 GRP2 10 11 1 1
#10 10 GRP2 11 12 1 1
#11 11 GRP2 12 13 1 1
#12 12 GRP2 13 14 1 1
#13 13 GRP2 14 14.3 0 1
#14 14 GRP2 14.3 15 0 1
#15 15 GRP2 15 16 1 1
данные
df <- structure(list(Sample.ID = 1:15, Groups = structure(c(1L, 1L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("GRP1",
"GRP2"), class = "factor"), From = c(2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 14.3, 15), To = c(3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 14.3, 15, 16), Zones = c(1L, 1L, 0L, 1L, 1L,
0L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 1L)), class = "data.frame",
row.names = c(NA, -15L))