【问题标题】:R: How select rows form a csv, that match rows of another csv in R?R:如何选择行形成一个csv,匹配R中另一个csv的行?
【发布时间】:2013-09-09 14:13:09
【问题描述】:

我有一个包含 3 列(物种名称、经度和纬度)的 csv 文件和另一个包含物种名称列的 csv 文件。我想要做的是从第一个 csv 中提取与第二个 csv 文件中的物种匹配的物种(也是长列和纬度列)。

如何在 R 中做到这一点?

【问题讨论】:

  • Read this 为您提供有关如何编写好问题并使其可重复的建议。

标签: r csv


【解决方案1】:
 ## 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,]

你得到:

 #> result
 #  Species Longitude  Latitude
 #2     Dog 0.6568743 0.5335943
 #3    Fish 0.8218709 0.2032832

【讨论】:

  • 非常感谢,这很有帮助。
  • 您的答案中的which 是不必要的。 result = file1[file1$Species %in% file2$Species, ] 给出相同的结果。
猜你喜欢
  • 2021-10-05
  • 1970-01-01
  • 1970-01-01
  • 2021-06-11
  • 1970-01-01
  • 1970-01-01
  • 2011-02-17
  • 2013-04-12
  • 2019-06-19
相关资源
最近更新 更多