删除数据框中的某些行

时间:2016-10-29 08:47:18

标签: r dataframe

我有一个数据框:

mydata <- data.frame(
  x1= as.factor(1:3), 
  x2= as.factor (4:6), 
  x3= as.factor(7:9), 
  x4= as.factor (2:7), 
  x5= as.factor(1:6), 
  x6= seq(0,600,len= 600),
  x7= seq(0,1,len=600)
  )

我希望在特定情况下删除其中的一些行。我是这样做的:

mydata1 <- mydata%>%
filter(x1==1, x2==4, x3==7, x4==2, x5==1)%>%
anti_join(mydata,., by=c("x1", "x2", "x3", "x4","x5","x6" "x7"))

mydata2 <- mydata1%>%
filter(x1==3, x2==6 x3==9, x4==7, x5==6)%>%
    anti_join(mydata1,., by=c("x1", "x2", "x3", "x4","x5","x6", "x7"))

我想删除很多行。还有另一种方法吗?

1 个答案:

答案 0 :(得分:2)

您可以将逻辑测试与&以及|结合使用。如果要删除满足以下所有内容的行

x1==1, x2==4, x3==7, x4==2, x5==1

然后这样做:

filter(mydata, !(x1 == 1 & x2 == 4 & x3 == 7 & x4 == 2 & x5 == 1))

行顺序不同,但结果相同:

md1 = filter(mydata, !(x1 == 1 & x2 == 4 & x3 == 7 & x4 == 2 & x5 == 1))
identical(arrange(md1, x6), arrange(mydata1, x6))
# [1] TRUE

您可以通过这种方式将条件合并为一个filter

md2 = filter(
  mydata,
  !(x1 == 1 & x2 == 4 & x3 == 7 & x4 == 2 & x5 == 1),
  !(x1 == 3 & x2 == 6 & x3 == 9 & x4 == 7 & x5 == 6)
)