I have two data frames, X and Y.
X <- data.frame(V1 = c("chr1", "chr1", "chr1", "chr2", "chr2", "ch2"),
Start = c(0, 540, 920, 0, 582, 715 ),
Stop = c(230, 720, 1270, 350, 635, 950))
Y <- data.frame(V1 = c("chr1", "chr1", "chr1", "chr2", "chr2", "ch2"),
Start = c(3, 16, 180,
15, 585, 800 ),
Stop = c(15, 24, 201,
102, 612, 850))
I want to obtain a data.frame Z which is a new data.frame with the info of X and the counts of Y between the range of each "X" row. For example, you can count 3 rows of "Y" which are between the range of the first row of "X" in chr1, so I have a 3 in "Z" in that row.
Z <- data.frame(V1 = c("chr1", "chr1", "chr2", "chr2", "chr2", "ch2"),
Start = c(0, 540, 920, 0, 582, 715 ),
Stop = c(230, 720, 1270, 350, 635, 950),
Count = c(3, 0, 0, 1, 1, 1))
I would appreciate some help, because until today I have only managed to print the number of rows if "X" dataset has only one row, but I don't know how to achieve my goal. I suppose I have to use some conditional statements plus a for loop to iterate over the rows of "X", but I don't know how to do it.
What I have tried:
Tried to calculate the number of rows that match the criteria with only one row in "Y":
nrow(Y[Y$Start >= X$Start & Y$Stop <= X$Stop, ])
Worked when there is only 1 row in "X", but not when I tried to implement it in a for loop.