按不同的值删除行

时间:2021-02-02 13:17:10

Here is an example of a DF:

以下是DF的示例:

v1<-c(1,1,1,1,2,2,2,2,3,3,3,3)
v2<-c(234,457,234,675,235,205,347,578,695,783,200,697)
v3<-c(528,659,102,236,358,562,987,102,235,474,888,362)
df<- data.frame(v1,v2,v3)

For this example my intention is to remove the row with the v1=1, v2=457 and v3=659.

对于此示例,我的目的是删除v1 = 1,v2 = 457和v3 = 659的行。

I'm trying different ways (subset or even []), for example:

我正在尝试不同的方式(子集或甚至[]),例如:

subset(df,df$v1!=1 & df$v2!=457 & df$v3!=659)
df[df$v1!=1 & df$v2!=457 & df$v3!=659,]

However in both cases all rows with v1=1 are removed. How should I write this in order that just the row with v1=1, v2=457 and v3=659 is removed?

但是,在这两种情况下,都删除了v1 = 1的所有行。为了只删除v1 = 1,v2 = 457和v3 = 659的行,我该怎么写呢?

So the final DF should be like this:

所以最终的DF应该是这样的:

v1<-c(1,1,1,2,2,2,2,3,3,3,3)
v2<-c(234,234,675,235,205,347,578,695,783,200,697)
v3<-c(528,102,236,358,562,987,102,235,474,888,362)
df<- data.frame(v1,v2,v3)

2 个解决方案

#1


1  

Close the conditions inside a bracket preceded by exclamation mark:

关闭括号内的条件,前面带有感叹号:

subset(df, !(df[,1] == 1 & df[,2] == 457 & df[,3] == 659))

#2


3  

This seems to be correct logic

这似乎是正确的逻辑

df[!(df$v1 == 1 & df$v2 == 457 & df$v3 == 659),]

What you are doing is removing all rows where v1!= 1 and v2!=457 and v3!=659

你正在做的是删除v1!= 1和v2!= 457和v3!= 659的所有行

> v1<-c(1,1,1,1,2,2,2,2,3,3,3,3)
> v2<-c(234,457,234,675,235,205,347,578,695,783,200,697)
> v3<-c(528,659,102,236,358,562,987,102,235,474,888,362)
> df<- data.frame(v1,v2,v3)

> df
   v1  v2  v3
1   1 234 528
2   1 457 659
3   1 234 102
4   1 675 236
5   2 235 358
6   2 205 562
7   2 347 987
8   2 578 102
9   3 695 235
10  3 783 474
11  3 200 888
12  3 697 362

> df[!(df$v1 == 1 & df$v2 == 457 & df$v3 == 659),]
   v1  v2  v3
1   1 234 528
3   1 234 102
4   1 675 236
5   2 235 358
6   2 205 562
7   2 347 987
8   2 578 102
9   3 695 235
10  3 783 474
11  3 200 888
12  3 697 362

#1


1  

Close the conditions inside a bracket preceded by exclamation mark:

关闭括号内的条件,前面带有感叹号:

subset(df, !(df[,1] == 1 & df[,2] == 457 & df[,3] == 659))

#2


3  

This seems to be correct logic

这似乎是正确的逻辑

df[!(df$v1 == 1 & df$v2 == 457 & df$v3 == 659),]

What you are doing is removing all rows where v1!= 1 and v2!=457 and v3!=659

你正在做的是删除v1!= 1和v2!= 457和v3!= 659的所有行

> v1<-c(1,1,1,1,2,2,2,2,3,3,3,3)
> v2<-c(234,457,234,675,235,205,347,578,695,783,200,697)
> v3<-c(528,659,102,236,358,562,987,102,235,474,888,362)
> df<- data.frame(v1,v2,v3)

> df
   v1  v2  v3
1   1 234 528
2   1 457 659
3   1 234 102
4   1 675 236
5   2 235 358
6   2 205 562
7   2 347 987
8   2 578 102
9   3 695 235
10  3 783 474
11  3 200 888
12  3 697 362

> df[!(df$v1 == 1 & df$v2 == 457 & df$v3 == 659),]
   v1  v2  v3
1   1 234 528
3   1 234 102
4   1 675 236
5   2 235 358
6   2 205 562
7   2 347 987
8   2 578 102
9   3 695 235
10  3 783 474
11  3 200 888
12  3 697 362