Merging multiple text files in R with a constraint

前端 未结 3 1462
小鲜肉
小鲜肉 2020-12-22 08:57

I have 10 text files containing 1000\'s of rows.

Example: First File:

V1  V2
1   2
2   3
10 20
1   4    
.....

Second file:

<
3条回答
  •  暖寄归人
    2020-12-22 09:47

    Try this example:

    #dummy files
    file1 <- read.table(text="V1  V2
    1   2
    2   3
    10 20
    1   4   ",header=TRUE)
    file2 <- read.table(text="
    V1  V2
    1   2
    8   10",header=TRUE)
    
    #make list of files - this can be done by lapply(list.files(),read.table)
    all_files <- list(file1,file2)
    
    #get unique pairs
    unique_pairs <- unique(do.call(rbind,all_files))
    #add new pair that is not in file1 and file2
    unique_pairs <- rbind(unique_pairs,c(33,22))
    
    #loop through pairs and files
    result <- sapply(1:nrow(unique_pairs),
                     function(x)
                       sapply(all_files,function(myfile){
                         #merge pair with file then check number of rows
                         d <- merge(myfile,unique_pairs[x,,drop=FALSE])
                         ifelse(nrow(d)==0,0,1)
                       }))
    
    #output
    cbind(unique_pairs,t(result))
    # V1 V2 1 2
    # 1   1  2 1 1
    # 2   2  3 1 0
    # 3  10 20 1 0
    # 4   1  4 1 0
    # 6   8 10 0 1
    # 61 33 22 0 0
    

提交回复
热议问题