-1

I have to merge 2 data files in R based on 3 variable. Is it necessary to sort both the data files by these 3 variables? Or R will be able to merge the files without sorting?

Main Data file:

`ID ` var1 var2 var3 Country  Segment Ind
 1     45   1    7      tt      tr      t
 2     55   4   6       gg      hh      h
 3     66   6    8       yy     yt      a

The data which have to merge with the Main data

   `ID `  Country  Segment Ind weight
     1      tt      yt      t   0.1
     2      yy      hh      h   0.12
     3      gg      tr      a  0.25

Based on Country segment and Ind Weight variable has to merge with the main file.

Thanks, Tanuvi

Tanuvi
  • 79
  • 4
  • 12
  • 2
    When joining two data frames, sorting isn't an issue, at least insofar as the ability for the join/merge to happen. Edit your question and please show us sample data and your expected output. – Tim Biegeleisen May 18 '17 at 10:29
  • 1
    What precluded you from simply testing it? – Roland May 18 '17 at 10:43
  • @Roland I couldn't test is as the data test is very huge,it is not possible to manually check.. – Tanuvi May 18 '17 at 10:48
  • @TimBiegeleisen, Thanks, I have edited the question. – Tanuvi May 18 '17 at 10:48
  • 1
    @Tanuvi As the current answer shows, you can always produce a minimal example. I'm quite serious. "Try and test" is an important skill for a programmer. You should not have needed to ask this question. – Roland May 18 '17 at 11:06
  • @Roland, Thanks for the feedback, I will test it in the future.. – Tanuvi May 18 '17 at 11:39

1 Answers1

2

no. you need not sort before merging (that is in SAS not in R)

> A1=NULL
> A1$city=c("York","London","Glasgow","Delhi","Atlanta")
> A1$key=1:5
> A1=as.data.frame(A1)
> A1
     city key
1    York   1
2  London   2
3 Glasgow   3
4   Delhi   4
5 Atlanta   5

and

> B1=NULL
> B1$rent=c("Expensive","Affordable")
> B1$key=c(5,1)
> B1=as.data.frame(B1)
> B1
        rent key
1  Expensive   5
2 Affordable   1

merge is very simple in R

> merge(A1,B1)
  key    city       rent
1   1    York Affordable
2   5 Atlanta  Expensive

Note I didnt have to sort B1 by key

Ajay Ohri
  • 3,382
  • 3
  • 30
  • 60