Merge two data frames and delete duplicate columns

I want to cbind two frames of data and delete duplicate columns. For example:

 df1 <- data.frame(var1=c('a','b','c'), var2=c(1,2,3)) df2 <- data.frame(var1=c('a','b','c'), var3=c(2,4,6)) cbind(df1,df2) #this creates a data frame in which column var1 is duplicated 

I want to create a data frame with columns var1 , var2 and var3 , in which the column var2 not repeated.

+7
source share
2 answers

merge will do the job.

to try:

 merge(df1, df2) 
+8
source

In case you inherit someone else's dataset and end up with duplicate columns and want to deal with them, this is a good way to do this:

 for (name in unique(names(testframe))) { if (length(which(names(testframe)==name)) > 1) { ## Deal with duplicates here. In this example ## just print name and column #s of duplicates: print(name) print(which(names(testframe)==name)) } } 
+1
source

All Articles