user3631848
user3631848

Reputation: 483

Extract the line with the same content from two files in R

I would like to use readLines function to read the text file line by line

69C_t.txt

Also, I would like to write a simple for loop with condition to extract the identical lines in two files.

69C_t <- "69C_t.txt"
conn <- file(69C_t,open="r")
t <-readLines(conn)
69C_b <- "69C_b.txt"
conn <- file(69C_b,open="r")
b <-readLines(conn)
for (i in 1:length(t)){
  for (j in 1:length(b)){
    if (i==j)
    write(t[i], file = "overlap.txt")
  }
}
close(tumor)

However, it seems only print out the first line. Can someone please have a check ?

Upvotes: 0

Views: 191

Answers (2)

Andrew Gustar
Andrew Gustar

Reputation: 18425

A faster approach would be, instead of the loop

writeLines(t[t %in% b],"overlap.txt")

Upvotes: 1

din
din

Reputation: 692

How about adding append in the write function: write(t[i], file = "overlap.txt", append = TRUE)

Upvotes: 0

Related Questions