【问题标题】:How do I compare two columns and delete the not overlapping elements?如何比较两列并删除不重叠的元素?
【发布时间】:2016-06-08 21:52:47
【问题描述】:

我在两个数据框中有两列,其中较长的一列包含另一列的所有元素。现在我想删除较长列中不与另一列重叠的元素以及相应的行。我使用以下方法确定了“差异”:

diff <- setdiff(gdp$country, tfpg$country)

我尝试使用两个 FOR 循环来完成这项工作:

for (i in 1:28) { for(j in 1:123) {if(diff[i] == gdp$country[j]) {gdp <- gdp[-c(j),]}}}

其中 28 是我要删除的行数(差异长度),而 123 是较长列的长度。这个不行,报错信息:

Error in if (diff[i] == gdp$country[j]) { : 
  missing value where TRUE/FALSE needed

那么我该如何解决这个问题?或者有更好的方法吗?

非常感谢。


我在这里有一个名为“gdp”的数据框:

  country  wto   y1990   y1991   y1992

Austria 1995  251540  260197  265644

Belgium 1995  322113  328017  333038

Cyprus 1995   14436   14537   15898

Denmark 1995  177089  179392  182936

Finland 1995  149584  140737  136058

France 1995 1804032 1822778 1851937

有 123 行。 我想删除在另一个向量中指定国家名称的行:

diff ["Austria","China",...,"Yemen"]

【问题讨论】:

  • 您能否发布最少的输入数据和预期输出,以便我们帮助编写工作代码?
  • 刚刚更新了示例...不确定是否有帮助 :) 谢谢!!
  • 如果你有:countriesToDelete &lt;- c('Austria', 'China', 'Yemen'),那么你可以过滤原始df如下:gdp[!gdp$country %in% countriesToDelete, ]
  • 这是完美的。解决了。谢谢!

标签: r dataframe compare


【解决方案1】:

还有更好的方法!您所描述的相当于左连接或内连接。但在 R 中,实现它的方法是使用合并命令:

## S3 method for class 'data.frame'
merge(x, y, by = intersect(names(x), names(y)),
  by.x = by, by.y = by, all = FALSE, all.x = all, all.y = all,
  sort = TRUE, suffixes = c(".x",".y"),
  incomparables = NULL, ...)

在你的情况下:

merge(gdp, tfpg, by = intersect('country', 'country'))

例如

x = data.frame(foo = c(1,2,3,4,5), bar=c("A","B","C","D","E"))
y = data.frame(baz = c(6,7,8,9), bar=c("A","C","E","F"))
z = merge(x,y,by=intersect('bar','bar'))

给予

  bar foo baz
1   A   1   6
2   C   3   7
3   E   5   8

【讨论】:

  • intersect('country', 'country') 似乎没有必要(只是by = "country" 应该这样做)
  • 有效!谢谢!!!这两个数据框没有相同的列,因此 merge() 将 tfpg 中的列合并到 gdp 中,但我可以简单地删除它们。 by = "country" 也可以。
猜你喜欢
  • 1970-01-01
  • 2019-03-22
  • 1970-01-01
  • 2016-01-18
  • 1970-01-01
  • 1970-01-01
  • 2012-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多