# Calculate height (y value) for elements of a vector based on the heights of the previous several elements.

This is one of many ways such a thing might be done.

``````library(data.table)
library(janitor)
library(tidyverse)
library(magrittr)
x1 <- c(1,1.5,2.7,3,4.75,9,11,15,15.1,18)
x2 <- c(2,4,3,7,6,9.5,17,15.6,24,19)
# x3 <- c((x1+x2)/2)

df<- data.frame(x1=x1,
x2=x2) %>% arrange(x1,x2)
df\$x3 <- (x1+x2)/2
df\$lag_x1<- lag(df\$x1)
df\$lag_x2<- lag(df\$x2)

df\$clash <-between(df\$x1,df\$lag_x1,df\$lag_x2) | between(df\$x2,df\$lag_x1,df\$lag_x2)
df\$height <- 1
for (i in seq_along(df\$clash))
{
if(i>1){
if(df\$clash[i])
df\$height[i] <- 1+ max(df\$height[i-1],0,na.rm = TRUE)
else
df\$height[i]<-1
}
}
df

labs <- as.character(df\$height)
colours = rep("red",length(df\$height))
par(bg="azure")
plot_left_lim <- min(df\$x1)
plot_right_lim <- max(df\$x2)
plot.new()
plot.window(c(plot_left_lim,plot_right_lim),c(0,6))
axis(1, at=seq(plot_left_lim,plot_right_lim,0.1), cex.axis=0.5)
abline(v=seq(plot_left_lim,plot_right_lim,0.05),col="gray95",lty="dotted")
abline(v=seq(plot_left_lim,plot_right_lim,0.1),col="lightgrey",lty="dotted")
abline(v=seq(plot_left_lim,plot_right_lim,0.5),col="lightgrey",lty="dashed")
abline(v=seq(plot_left_lim,plot_right_lim,1),col="darkgrey")
segments(df\$x1,df\$height,df\$x2,df\$height,col=colours,lwd=10)
text(df\$x3,df\$height+.5,labs,cex=0.5,srt=-45)
title(main="Elution Times of Compounds on EO Basemethod 2020.M")
title(xlab="Elution Time in Minutes")
abline(v=plot_left_lim)
abline(v=plot_right_lim)
segments(plot_left_lim,6.25,plot_right_lim,6.25)
``````