Purrr根据包含字符向量的无效变量过滤嵌套数据

时间:2018-05-01 22:06:28

标签: r dplyr tidyverse purrr

我的数据类似于df3。要重现数据,请运行以下命令:

vec1 <- c("A", "B")
vec2 <- c("A", "B", "C")

df1 <- tibble::tribble(
          ~A, ~B,
          "X", 4L,
          "X", 9L,
          "Y", 5L,
          "Y", 2L,
          "Y", 8L,
          "Y", 2L) %>%
  group_by(A) %>% 
  nest()

df2 <- tibble::tribble(
  ~A, ~C,
  "X", vec1,
  "Y", vec2)

df3 <- df1 %>% left_join(df2, by = "A")

我需要使用以下内容过滤嵌套数据:

df4 <- df3 %>% filter(when C==vec1, B (part of nested data now) < 5 
                      when C==vec2, B (part of nested data now) >4)

或者可能是这样的:

df4 <- df3 %>% map(.$data, ~filter((identicle(.$C, vec1) & B < 5) | 
                                  identical(.$C, vec2) & B >4))

我只有df3,我想要df4。如何使用purrr进行上述过滤以获得以下所需的df4输出。

df11 <- tibble::tribble(
  ~A, ~B,
  "X", 4L,
  "Y", 5L,
  "Y", 8L) %>%
  group_by(A) %>% 
  nest()

df4 <- df11 %>% left_join(df2, by = "A")

3 个答案:

答案 0 :(得分:3)

以下是使用map2identical进行条件检查的一个选项:

df3 %>% 
    mutate(
        data = map2(
            data, C, ~ if(identical(.y, vec1)) filter(.x, B < 5) else filter(.x, B > 4)
        )
    ) %>% 
    identical(df4)
# [1] TRUE

答案 1 :(得分:1)

以下是一种不同的方法,使用unnest直接处理B的值,然后替换原始向量。

library(tidyverse)
vec1 <- c("A", "B")
vec2 <- c("A", "B", "C")

df3 <- structure(list(A = c("X", "Y"), data = list(structure(list(B = c(4L, 9L)), .Names = "B", row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame")), structure(list(B = c(5L, 2L, 8L, 2L)), .Names = "B", row.names = c(NA, -4L), class = c("tbl_df", "tbl", "data.frame"))), C = list(c("A", "B"), c("A", "B", "C"))), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -2L), .Names = c("A", "data", "C"))

veclist <- list(vec1, vec2)
df3 %>%
  mutate(vec = match(C, veclist)) %>%
  unnest(data) %>%
  filter(vec == 1 & B < 5 | vec == 2 & B > 4) %>%
  nest(B) %>%
  mutate(C = map(vec, ~ veclist[[.]])) %>%
  as.data.frame()
#>   A vec data       C
#> 1 X   1    4    A, B
#> 2 Y   2 5, 8 A, B, C

as suggested by Ansgar Wiechers(v0.2.0)创建于2018-05-01。

答案 2 :(得分:1)

不需要if-else语句:

mine=df3%>%
   mutate(data=map2(data,match(C,list(vec1,vec2)),
                ~filter_(.x,c("B<=4","B>4")[.y])))
 identical(mine,df4)
[1] TRUE