0

I have several txt files in which each txt file contains 3 columns(A,B,C). Column A will be common to all txt files. Now I want to combine txt files with coulmn A appearing only once while the other columns (B and C) of respective files. I used cbind but it creates a data frame with repeats of column A, which I dont want. The column A must be repeated only once. Here is the R code I tried:

data <- read.delim(file.choose(),header=T)   
data2 <- read.delim(file.choose(),header=T)
data3 <- cbind(data1,data2)
write.table(data3,file="sample.txt",sep="\t",col.names=NA)

1 Answer 1

8

Unless your files are all sorted precisely the same, you'll need to use merge:

dat <- merge(data,data2,by="A")
dat <- merge(dat,data3,by="A")

This should automatically prevent you from having multiple A's, since merge knows they're all a key/index column. You'll likely want to rename the duplicate B's and C's before merging.

Sign up to request clarification or add additional context in comments.

1 Comment

gsk3's solution is also better than cbind because it doesn't require assuming that the A values are identical matches. If, for instance, the A values (rows) are permuted, gsk3's solution will still give the right answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.