根据多列之间的连接删除数据框的行

时间:2014-01-25 21:37:01

标签: r

考虑以下数据框:

# input 
a <- data.frame(
  X1=c("a","a","a","a","a","a","a","a","a","a","a","b","b","b","b","b","b","b","b","b"),
  X2=c(2,4,6,2,4,7,9,5,4,7,3,5,8,4,3,5,7,6,3,5),
  X3=c(5,6,1,4,7,5,5,4,4,2,5,4,5,2,4,7,3,5,3,7)
)

如何删除任何行,它在变量2和变量3方面都小于另一行,其中两行具有相同的因子级别(变量1)?

E.G。

a[1,1]==a[2,1] and
a[1,2]<a[2,2] and 
a[1,3]<a[2,3] then a[1,] should be removed.

# output 

a <- data.frame( X1=c("a","a","a","a","b","b","b","b"), 
                 X2=c(4,4,7,9,8,5,6,5), 
                 X3=c(6,7,5,5,5,7,5,7) ) 

2 个答案:

答案 0 :(得分:3)

如果速度不是您的主要考虑因素,我认为这是非常易读的:

library(plyr)
ddply(a, "X1", function(x) {
  n <- seq_len(nrow(x))
  m <- outer(n, n, Vectorize(function(i,j) all(x[i, 2:3] < x[j, 2:3])))
  i <- rowSums(m) > 0L
  return(x[!i, ])
})

其中mTRUEFALSE的矩阵,表示行i是否由行j支配,i的所有组合}和j

答案 1 :(得分:2)

函数isRemoved将为TRUEFALSE提供每行i的条件:

isRemoved = function(i, a) {
  out = logical(nrow(a))
  for(j in 1:nrow(a)) {
    out[j] = a[i,1]==a[j,1] & a[i,2]<a[j,2] & a[i,3]<a[j,3]
  }
  out = any(out)
  return(out)
}

然后,您可以将其应用于所有行:

remove = sapply(1:nrow(a), isRemoved, a=a)

并保留您想要的行:

a.new = a[!remove, ]

a.new 

   X1 X2 X3
2   a  4  6
5   a  4  7
6   a  7  5
7   a  9  5
13  b  8  5
16  b  5  7
18  b  6  5
20  b  5  7