简体   繁体   English

dplyr:基于向量的过滤器

[英]dplyr: Filter based on a vector

I assume the error is in the code and therefore I think this example is enough.我认为错误在代码中,因此我认为这个例子就足够了。

I wanted to filter my df (df2) according to the vector i created.我想根据我创建的向量过滤我的 df (df2)。 This vector was created extracting information from a column of another data frame (df1).该向量是从另一个数据框 (df1) 的列中提取信息而创建的。

Vector based on df1: (extracting the 3rd column of df1)基于df1的向量:(提取df1的第3列)

 vector_df1 <- df1 [, 3]

Trying to apply filter on df2, based on the vector_df1尝试基于 vector_df1 在 df2 上应用过滤器

Filter_df2 <- df2 %>%
                    
               filter(Column_df2 %in% vector_df1)

Results: 0 rows结果:0 行

Can someone help me see what I'm doing wrong有人可以帮我看看我做错了什么

thanks in advance提前致谢

This is a case of structure of dataset ie with data.frame , if we use [,col] , it uses drop = TRUE and coerces it to vector , while for data.table or tibble , by default, it is drop = FALSE , thus returning the tibble itself with single column.这是数据集结构的情况,即data.frame ,如果我们使用[,col] ,它使用drop = TRUE并将其强制转换为vector ,而对于data.tabletibble ,默认情况下它是drop = FALSE ,因此返回小标题本身带有单列。 The documentation can be found in ?Extract .该文档可以在?Extract中找到。 Safe option is [[ which have the same behavior in extraction of column as a vector安全选项是[[在提取列时具有与vector相同的行为

vector_df1 <- df[[3]]

According to ?Extract , the default usage is根据?Extract ,默认用法是

x[i, j, ... , drop = TRUE] x[i, j, ... , drop = TRUE]

and it is specified as它被指定为

or matrices and arrays.或矩阵和 arrays。 If TRUE the result is coerced to the lowest possible dimension (see the examples).如果为 TRUE,则将结果强制转换为可能的最低维度(参见示例)。 This only works for extracting elements, not for the replacement.这仅适用于提取元素,不适用于替换。 See drop for further details.有关详细信息,请参阅下降。

The documentation for tibble can be found in ?"tbl_df-class" tibble的文档可以在?"tbl_df-class"中找到

df[, j] returns a tibble; df[, j] 返回一个小标题; it does not automatically extract the column inside.它不会自动提取里面的列。 df[, j, drop = FALSE] is the default. df[, j, drop = FALSE] 是默认值。 Read more in subsetting.在子集中阅读更多内容。

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

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