r - 如何根据列中的两个值过滤行?

对 R 完全陌生,我尝试使用 dplyr 包解决这个问题。我想过滤掉并返回同时具有 Import 和 Export 值的国家并分别查看它们。 select、filter等很多方法都试过了,都不行。

Country Year    Quantity    Description Import/Export
A   2001    10  Frozen  Export
B   2001    50  Fresh   Import
B   2004    20  Frozen  Export
C   2003    30  Frozen  Import
C   2005    40  Fresh   Export
C   2006    60  Frozen  Import
D   2007    290 Fresh   Import

理想情况下,最终结果应该是这样的:

Country Year    Quantity    Description Import/Export
B   2001    50  Fresh   Import
B   2004    20  Frozen  Export
C   2003    30  Frozen  Import
C   2005    40  Fresh   Export
C   2006    60  Frozen  Import

最佳答案

我们可以group_by() Country,然后用any "Import/Export"=='Import' and any "过滤所有组"导入/导出""== '导出'

library(dplyr)

df %>% group_by(Country) %>%
        filter(any(`Import/Export`=='Import') & 
               any(`Import/Export`=='Export')) %>%
        ungroup()

# A tibble: 5 x 5
  Country  Year Quantity Description `Import/Export`
  <chr>   <dbl>    <dbl> <chr>       <chr>          
1 B        2001       50 Fresh       Import         
2 B        2004       20 Frozen      Export         
3 C        2003       30 Frozen      Import         
4 C        2005       40 Fresh       Export         
5 C        2006       60 Frozen      Import 

数据

structure(list(Country = c("A", "B", "B", "C", "C", "C", "D"), 
    Year = c(2001, 2001, 2004, 2003, 2005, 2006, 2007), Quantity = c(10, 
    50, 20, 30, 40, 60, 290), Description = c("Frozen", "Fresh", 
    "Frozen", "Frozen", "Fresh", "Frozen", "Fresh"), `Import/Export` = c("Export", 
    "Import", "Export", "Import", "Export", "Import", "Import"
    )), row.names = c(NA, -7L), class = c("tbl_df", "tbl", "data.frame"
))

https://stackoverflow.com/questions/69143212/

相关文章:

python - AES CTR解密: Cryptography and Cryptodome gi

c# - Parallel.Foreach 和每个产生不同的结果 : Why is my code

c++ - 在 constexpr 分支中使用枚举类值

python - Azure Databricks python 命令显示当前集群配置

flutter - 如何在 flutter 中的行之间写 OR

c++ - 在 "Effective Modern C++"示例中在索引运算符之前使用 std::f

docker - 使用 deps.edn 在容器中安装依赖项

c# - 如何在 C# 中使用预处理器指令仅在 Windows 10 上执行一些代码?

c - 有没有办法从未知字节设置/清除位,同时保持所有其他位不变?

c - 栈在使用Pthread的多线程程序中是如何工作的?