0

Hello i would like to know how can i merge 2 data frames in R,there is a merge function ,but i would like to do this :

data frame1
  X Y Z
1  1 1 1  
2  1 1 1
3  1 1 1
4  1 1 1
5  1 1 1

data frame 2
  A B C
1 2 2 2
2 2 2 2
3 2 2 2



mergedataframe
  X Y Z A B C 
1 1 1 1  
2 1 1 1 
3 1 1 1 2 2 2
4 1 1 1 2 2 2
5 1 1 1 2 2 2

the think is i must synchronize 3 csv files (dataframe) and i have no idea how to it with R.

if somebody have any idea about it ,thank u

i redit my post i would like my merged data frame like that :

data frame1

        X Y Z
    1  1 1 1  
    2  1 1 1
    3  1 1 1
    4  1 1 1
    5  1 1 1
    6  1 1 1

data frame 2
  A B C
1 2 2 2
2 2 2 2




mergedataframe
  X Y Z A B C 
1 1 1 1  
2 1 1 1 
3 1 1 1 2 2 2
4 1 1 1 2 2 2
5 1 1 1 
6 1 1 1

1 Answers1

0
df1 <- data.frame(X=rep(1,5),Y=1, Z=1)
df2 <- data.frame(A=rep(2,3),B=2, C=2)
#rownames(df2) <- 3:5
rownames(df2) <- tail(rownames(df1), nrow(df2))

mergedataframe <- merge(df1,df2, by=0, all=TRUE)
mergedataframe <- mergedataframe[,-1]
mergedataframe

  X Y Z  A  B  C
1 1 1 1 NA NA NA
2 1 1 1 NA NA NA
3 1 1 1  2  2  2
4 1 1 1  2  2  2
5 1 1 1  2  2  2
Marc in the box
  • 11,769
  • 4
  • 47
  • 97
  • thank u for you answer but i does not work like i expected ,i must merge my dataframe in the line 3 (like in your post ) but your code give me a simple merge – developer365 Apr 03 '14 at 12:41
  • I don't understand what you want then - what do you mean by a "simple merge"? – Marc in the box Apr 03 '14 at 12:43
  • `by = 0` merges by rowname. Thus, if you want to place df2 'at the end' of df1, you need to add row names from the `tail` end of df1 to df2: `rownames(df2) <- tail(rownames(df1), nrow(df2))` before merging. – Henrik Apr 03 '14 at 12:48
  • i would like to merge my second dataframe with the first when i'am on the line 3 ,your code gives me NA in the last 2 observations – developer365 Apr 03 '14 at 12:50
  • thank u for your answer guys ,like Henrik said i just put rownames(df2) <- tail(rownames(df1), nrow(df2)) before merging .Juste another question if i have 2 data frame (df1 has 100 lines and df2 has 30 and i would like to do the merge in the line 50 of df1 ,how can i do it? ),thank u again – developer365 Apr 03 '14 at 13:01
  • Sorry, I think I had accidentally deleted the line where I added the other rownames – Marc in the box Apr 03 '14 at 13:06
  • @Henrik, ok i understand (y) – developer365 Apr 03 '14 at 13:23
  • for my last question there is another function who do it ,or i must program it !! thank u again for your answers . – developer365 Apr 03 '14 at 13:32
  • I think you will need to program this - It's relatively simple: use the row names of your data.frames to guide the merge function on how to combine. – Marc in the box Apr 03 '14 at 14:37