1

I have one csv file which contains 3 columns (species name, longitude, and latitude.) and a second csv file which contains a column with species names. What I want to do is to extract from the first csv the species (also the long and lat columns) that match the species in the second csv file.

How can I do this in R?

Dimitris K.
  • 65
  • 1
  • 2
  • 9
  • 2
    [Read this](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for you to have an advice on how to write a good question and make it reproducible. – Jilber Urbina Sep 09 '13 at 14:18

1 Answers1

4
 ## Read csv files
 file1 = read.csv(paste(path, "file1.csv", sep = ""), stringsAsFactors = FALSE, na.strings = "NA")
 file2 = read.csv(paste(path, "file2.csv", sep = ""), stringsAsFactors = FALSE, na.strings = "NA")


 #> file1
 #  Species Longitude   Latitude
 #1     Cat 0.4300052 0.04554442
 #2     Dog 0.6568743 0.53359425
 #3    Fish 0.8218709 0.20328321
 #4    Deer 0.4601183 0.93191142
 #5     Cow 0.9975495 0.02349226


 #> file2
 #  Species
 #1    Fish
 #2     Dog


 ## Get subset in first file of species in second file
 result = file1[file1$Species %in% file2$Species,]

You get:

 #> result
 #  Species Longitude  Latitude
 #2     Dog 0.6568743 0.5335943
 #3    Fish 0.8218709 0.2032832
Mayou
  • 8,498
  • 16
  • 59
  • 98
  • 1
    The `which` in your answer is unnecessary. `result = file1[file1$Species %in% file2$Species, ]` gives the same result. – Gregor Thomas Sep 09 '13 at 16:29