如何删除表中不在列表中的条目

时间:2018-01-15 10:51:21

标签: r

我只知道非常基本的R,所以请原谅我,如果这有明显的答案。

所以我有一个包含两列的表(让我们称之为A)和一个包含一列(B)的表。我希望RStudio查看A的第二列,并删除不在B中的每个条目。例如,如果数字0007在A的第二列中,但它不在B中,则删除0007的行。

I've tried this solution but I don't think it's what I'm looking for since it threw up an error.

我认为它会在for循环中出现某种for循环,但这就是我所得到的。

2 个答案:

答案 0 :(得分:1)

你可以在下面试试。希望这有帮助!

#sample data - (since OP has not provided any sample data I cooked my own)
A <- data.frame(A_col1=c(3,4,5,6,7),
                A_col2=c('abc','qwerty','007','asdf', 'qwerty'))
B <- data.frame(B_col1=c('abc','qwerty','asdf','prem'))

A_new <- A[A$A_col2 %in% B$B_col1,]
A_new

输出是:

  A_col1 A_col2
1      3    abc
2      4 qwerty
4      6   asdf
5      7 qwerty

您可以注意到B中没有007,因此相应的行已被删除。

答案 1 :(得分:0)

这会有用吗?

A <- matrix(c("a", "b", "c", "0003", "0007", "0005"), nrow = 3)
B <- matrix(c("0003", "0004", "0005"), nrow = 3)
res <- A[A[, 2] %in% B[, 1], ]
res
         [,1] [,2]  
[1,] "a"  "0003"
[2,] "c"  "0005"