Combine two data frames and remove duplicate columns

 ̄綄美尐妖づ 提交于 2019-12-04 00:54:17

问题


I want to cbind two data frames and remove duplicated 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 column var2 is not repeated.


回答1:


merge will do that work.

try:

merge(df1, df2)



回答2:


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

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))
  }
}


来源:https://stackoverflow.com/questions/7440917/combine-two-data-frames-and-remove-duplicate-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!