简体   繁体   中英

R : Combine multipe data frame with multiple identical columns in r without duplicating columns ?

I have about 2 data frames, each one has 13 columns like this way :

1st dataframe :

"ID"       "Product" "Date"     "Year" "Month" "KKK_01" "PPP_01" "Output_01"
 SD54d      Pcsq1     2016/02/01  2016  02      1253.25   2563.2   6936
 AD152      P25       2001/06/12  2001  06      1200025   25080    983.01
 26zad      P*896     2012/03/10  2012  03      15647.1   256      99874

1st dataframe :

"ID"       "Product" "Date"     "Year" "Month" "KKK_02" "PPP_02" "Output_02"
 SD54d      Pcsq1     2016/02/01  2016  02      50       5063      3.26
 EDADA      SP?DEJ    2001/06/12  2001  06      9997     25080     9
 26zad      P*896     2012/03/10  2012  03       0        887      189

It's possible that the same ID client existe in both data frame. In this case, only the columns

"KKK_(index)" "PPP_(index)" "III_(index)"  "Output_(index)"

will change.

Finaly, I want to combine both data frames without duplicating the identical columns: "ID" "Product" "Date" "Year" "Month"

finaldataframe :

 "ID"      "Product"     "Date"   "Year" "Month" "KKK_01" "PPP_01" "Output_01" "KKK_02" "PPP_02" "Output_02" 
  SD54d      Pcsq1     2016/02/01  2016  02      50       5063      3.26           50       5063      3.26
  AD152       SP?DEJ    2001/06/12  2001  06     9997     25080     9              0          0       0  
  26zad      P*896     2012/03/10  2012  03      0        887       189            0          0       0  
  EDADA      SP?DEJ    2001/06/12  2001  06      0         0        0             25          9       3

I tried to merge with "ID" but it didn't work.

 dataframe1=merge(dataframe1, dataframe2, all=T)

I even tried to replace the na after values after the merge but I get error

invalid factor level, Na generated 

Your help is very much appreciated !

Try to convert every factor columns in character columns and do your merging again :

#col = Your column name
dataframe1[,col] <- as.character(datframe1[,col])

Your code work on mine configuration.

Hope that's will work

Gottavianoni

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM