I am trying to automatize the calculation of some ranges that have to be integrated later on. I am doing it without using tidyR, but I believe that applying tidy could help solve the last bottle neck of my problem My initial table looks like this:
int_NMR <- data.frame("Component" = c("A", "B", "C", "D", "E",
"F", "G", "H"),
"From" = c(0.0, 45.0, 60.0, 95.0, 110.0, 145.0, 165.0, 190),
"To" = c(45.0, 60.0, 95.0, 110.0, 145.0, 165.0, 190.0, 215.0))
to the "From" and "To" values I have to add or substract an X value (for example 160). However, this implies that some ranges will overlap and then need to be sliced and the column "component" be kept for both slices.
The end result would look something like this:
As you can see some have been sliced and there is an overlap that needs to be mantained, for instance the component A, which initially goes from 0 to 45, now is going from 0 to 5, from 5 to 30 and from 30 to 45, and overlaping with components F_low, G_low and H_low.
The approach that I have followed is to bind tables with NAs on them but when I arrive to the last table, the overlaping ranges can not be sliced without me loosing the information of which component it belongs.
Below my code
na_frame <- NULL
int_NMR_all<- NULL
int_NMR_high <- data.frame(setNames(lapply(int_NMR[1], function(x) paste("ssb_high", x, sep="_")),"Component_ssb"),int_NMR[2:3]+sb_ofset)
int_NMR_low <- data.frame(setNames(lapply(int_NMR[1], function(x) paste("ssb_low", x, sep="_")),"Component_ssb"),int_NMR[2:3]-sb_ofset)
int_NMR_all <- rbind(int_NMR_low,int_NMR_high)
na_frame <- as.data.frame(matrix(NA, nrow = nrow(int_NMR), ncol = 3))
names(na_frame) <- names(int_NMR_all)
int_NMR_all <- rbind(int_NMR_all, na_frame)
na_frame <- as.data.frame(matrix(NA, nrow = nrow(int_NMR_all), ncol = 1))
names(na_frame) <- c("Component")
int_NMR_all<- cbind(int_NMR_all, na_frame)
na_frame <- as.data.frame(matrix(NA, nrow = nrow(int_NMR), ncol = 1))
names(na_frame) <- c("Component_ssb")
int_NMR<- cbind(int_NMR, na_frame)
na_frame <- as.data.frame(matrix(NA, nrow = 2*nrow(int_NMR), ncol = 4))
names(na_frame) <- names(int_NMR_all)
int_NMR <- rbind(int_NMR, na_frame)
int_NMR_all <- rbind(int_NMR,int_NMR_all)
int_NMR_all <- int_NMR_all[!is.na(int_NMR_all$From),]

Here is a
data.tableapproach, also using theintervalSurgeon-package for finding unique intervals.Probably not thje most efficient way, but output looks as desired..
final