[R] Merging by matching two columns

arun smartpink111 at yahoo.com
Thu May 29 13:32:06 CEST 2014


Hi,
I need to merge two data sets but I need them to match two columns, not just one. For example:

Hi,

If 'dat1` and 'dat2` are the two datasets.
 merge(dat1,dat2,by=c("plant.species","insect.species"),all=TRUE)
#  plant.species insect.species visit.freq no.grains
#1           p.A            i.1          5        51
#2           p.A            i.2          4        NA
#3           p.A            i.3          1         2
#4           p.B            i.2          2        21
#5           p.B            i.3         10         0
#6           p.C            i.1          2        NA
#7           p.C            i.4          6        NA

A.K.


Dataset 1, frequency of visits of different insect species to different plant species. Some plants are visited by more than one species of insects, and viceversa:

plant.species     insect.species    visit.freq
p.A                   i.1                    5
p.A                   i.2                    4
p.A                   i.3                    1  
p.B                   i.2                    2
p.B                   i.3                    10
p.C                   i.1                    2
p.C                   i.4                    6

Dataset 2, number of pollen grains transferred by the different insect species for the different plant species

plant.species     insect.species    no.grains
p.A                   i.1                    51
p.A                   i.3                    2  
p.B                   i.2                    21
p.B                   i.3                    0

The datasets are not identical as some plant-insect combinations is in one but not in the other.

I need to merge both datasets making sure that both columns, "plant.species" and "insect.species", match.

I have used the merge function before, but only matching by one column, either plantor insect species, for example. Hope it's clear.

Thanks, Silvia. 




More information about the R-help mailing list