Matched Range Merge in R

前端 未结 3 1363
甜味超标
甜味超标 2020-12-22 03:55

I would like to merge/combine two files, so that if an entry in column B of my first file falls into the range of columns B and C in my second file, the output will contain

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-22 04:22

    Something like this should do the trick. You could probably make it more concise, but to elucidate all the steps I made it overly obvious.

    NewMatrixCol1 <- c()
    NewMatrixCol2 <- c()
    NewMatrixCol3 <- c()
    NewMatrixCol4 <- c()
    NewMatrixCol5 <- c()
    
    for (i in 1:length(file1$A)) {
        for (j in 1:length(file2$A)) {
            LowNumber <- file2$B[j]
            HighNumber <- file2$C[j]
            if (LowNumber <= file1$B[i] & file1$B[i]  <= HighNumber) {
                append(NewMatrixCol1, file1$A[i])
                append(NewMatrixCol2, file1$B[i])
                append(NewMatrixCol3, file2$A[j])
                append(NewMatrixCol4, file2$B[j])
                append(NewMatrixCol5, file2$C[j])
            } else {}
        }
    }
    
    dataframe <- data.frame(Col1 = NewMatrixCol1, Col2 = NewMatrixCol2, Col3 = NewMatrixCol3, Col4 = NewMatrixCol4, Col5 = NewMatrixCol5)
    

    EDIT1: I misunderstood the question, and am now working on it.

    EDIT2: This new solution should work as indicated.

    EDIT3: There was a missing ), as indicated by mfk534.

提交回复
热议问题