简体   繁体   English

在R中,如何通过另一个数据框的列名删除数据框中的行?

[英]In R, how do I delete rows in a data frame by column names of another data frame?

I have one dataframe (df1) with more than 200 columns containing data (several thousands of rows each). 我有一个数据帧(df1),其中包含超过200列包含数据(每行数千行)。 Column names are alphanumeric and all distinct from each other. 列名是字母数字,并且彼此不同。

I have a second dataset (df2) with a couple of columns where the first column (named 'col1') contains rows with "values" carrying colnames of df1. 我有第二个数据集(df2),其中有几列,其中第一列(名为'col1')包含带有“值”的行,其中包含df1的共同名称。

But not for every row in df2 I have a corresponding column in df1. 但是对于df2中的每一行都没有,我在df1中有一个相应的列。

Now I would like to delete (drop) all rows in df2 where there is no "corresponding" column in df1. 现在我想删除(删除)df2中df1中没有“对应”列的所有行。

I searched quite a while using keywords like "subset data.frame by values from another data.frame" but did not find any solution. 我搜索了很长一段时间,使用了像“来自另一个data.frame的值的子集data.frame”这样的关键字,但没有找到任何解决方案。 I checked, eg here , here or here and some other places. 我检查过,例如这里这里这里以及其他一些地方。

Thanks for your help. 谢谢你的帮助。

Data: 数据:

df1 <- data.frame(a = 1:3, b = 1:3)
#   a b
# 1 1 1
# 2 2 2
# 3 3 3

df2 <- data.frame(col1 = c("a", "c"))
#   col1
# 1    a
# 2    c

Keep rows in df2 whose values are names in df1 : 保留df2的行,其值为df1中的名称:

subset(df2, col1 %in% names(df1))
#   col1
# 1    a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM