Ayush Raj Singh
Ayush Raj Singh

Reputation: 873

How to merge columns of two files in R?

I have two files A and B:

First file A has columns whose names are as follows:

names(A) <- c("a","b","c","d","e","f")

Second file B has columns whose names are as follows:

names(B) <- c("b","c","d","y","z","q")

You see some column names are same but some are not. I want to have all columns in both files.

So finally both of them should like:

names(A) <- c("a","b","c","d","e","f",y","z","q")

names(B) <- c("a","b","c","d","e","f","y","z","q")

with new columns in both files which were earlier not present with NA values of course.

I am looking for some function in R which can do this.

Any help would be greatly appreciated.

Upvotes: 0

Views: 145

Answers (1)

Hong Ooi
Hong Ooi

Reputation: 57686

notA <- setdiff(names(B), names(A))
notB <- setdiff(names(A), names(B))

A[notA] <- NA
B[notB] <- NA

If you also want to have the column names in the same order in both datasets:

B <- B[names(A)]

Upvotes: 4

Related Questions