我有类似于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。我应该如何使用咕噜声进行上述过滤以获得以下所需的 df4 输出。
df11 <- tibble::tribble(
~A, ~B,
"X", 4L,
"Y", 5L,
"Y", 8L) %>%
group_by(A) %>%
nest()
df4 <- df11 %>% left_join(df2, by = "A")
以下是使用map2
和identical
进行条件检查的一个选项:
df3 %>%
mutate(
data = map2(
data, C, ~ if(identical(.y, vec1)) filter(.x, B < 5) else filter(.x, B > 4)
)
) %>%
identical(df4)
# [1] TRUE
这是一种不同的方法,它使用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
创建于 2018-05-01 由 reprex 软件包 (v0.2.0(.
不需要 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