R语言 使用命名列表过滤用于特定变量组合的框架

svmlkihl  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(91)

我想用一个命名列表来过滤一个嵌套的嵌套框架中的特定变量组合,但我无法排除一些不需要的组合。下面是一个示例:

library(tidyverse)

# Create fake data
set.seed(1234)
data <- tibble(
    c1 = rep(letters[1:3], each = 10),
    c2 = sample(letters[4:6], size = 30, replace = T),
    var1 = rnorm(30),
    var2 = rnorm(30)
)
nested_data <- data %>% 
    nest(.by = c(c1, c2))

# Create list of the specific combinations I want
criteria <- list(a = c("d", "e"), b = "d")

我尝试使用函数names()unique()来完成,但结果并不排除具有重叠条件的不需要的组合。

# Filter for the specific combinations
c1_criteria <- names(criteria)
c2_criteria <- unique(unlist(criteria))
nested_data %>% 
    filter(c1 %in% c1_criteria,
           c2 %in% c2_criteria) %>% 
    unnest(data)

这是输出

# A tibble: 4 × 3
  c1    c2    data            
  <chr> <chr> <list>          
1 a     e     <tibble [5 × 2]>
2 a     d     <tibble [3 × 2]>
3 b     e     <tibble [6 × 2]>
4 b     d     <tibble [1 × 2]>

我只打算有以下组合:
c1 == "a" & c2 == "d"c1 == "a" & c2 == "e"c1 == "b" & c2 == "d
但是,输出还包括组合c1 == "b" & c2 == "e"。因此,预期输出如下:

# A tibble: 3 × 3
  c1    c2    data            
  <chr> <chr> <list>          
1 a     e     <tibble [5 × 2]>
2 a     d     <tibble [3 × 2]>
3 b     d     <tibble [1 × 2]>

我想可能有一种方法可以从命名列表criterias生成一个特定逻辑条件的列表,并将其作为参数提供给过滤器函数,但我不确定如何做到这一点。

dhxwm5r4

dhxwm5r41#

我们可以将该列表转换为一个包含c1和c2的组合的2列过滤表,然后它可以与semi_join()一起使用:

library(tidyverse)

set.seed(1234)
data <- tibble(
  c1 = rep(letters[1:3], each = 10),
  c2 = sample(letters[4:6], size = 30, replace = T),
  var1 = rnorm(30),
  var2 = rnorm(30)
)
nested_data <- data %>% 
  nest(.by = c(c1, c2))

criteria <- list(a = c("d", "e"), b = "d")

enframe(criteria, "c1", "c2") %>% 
  unnest(c2) %>% 
  semi_join(nested_data, .)
#> Joining with `by = join_by(c1, c2)`
#> # A tibble: 3 × 3
#>   c1    c2    data            
#>   <chr> <chr> <list>          
#> 1 a     e     <tibble [5 × 2]>
#> 2 a     d     <tibble [3 × 2]>
#> 3 b     d     <tibble [1 × 2]>

列出转换步骤:

enframe(criteria, name = "c1", value = "c2")
#> # A tibble: 2 × 2
#>   c1    c2       
#>   <chr> <list>   
#> 1 a     <chr [2]>
#> 2 b     <chr [1]>

enframe(criteria, "c1", "c2") %>% unnest(c2)
#> # A tibble: 3 × 2
#>   c1    c2   
#>   <chr> <chr>
#> 1 a     d    
#> 2 a     e    
#> 3 b     d

创建于2023-10-02使用reprex v2.0.2

相关问题