首页 > 解决方案 > 我可以省略 r 中数据集的搜索结果吗?

问题描述

我在数据库方面的第一份工作是在 FileMaker Pro 中。我真正喜欢的功能之一是能够进行复杂的搜索,然后通过一次调用,忽略这些结果并返回原始数据集中未在搜索中返回的任何内容。有没有办法在 R 中做到这一点而不必翻转搜索中的所有逻辑?

就像是:

everything_except <- df %>%
  filter(x == "something complex") %>% 
  omit()

我最初的想法是考虑使用连接来保持不匹配的值,但我想我会看看是否有不同的方法。

更新示例:我有点犹豫是否要添加示例,因为我不想仅仅解决这个问题,但要了解是否存在适用于多种情况的基础方法。

set.seed(123)
event_df <- tibble(time_sec = c(1:120)) %>% 
  sample_n(100) %>%
  mutate(period = sample(c(1,2,3),
                         size = 100,
                         replace = TRUE),
         event = sample(c("A","B"), 
                        size = 100, 
                        replace = TRUE, 
                        prob = c(0.1,0.9))) %>% 
  select(period, time_sec, event) %>% 
  arrange(period, time_sec)

filter_within_timeframe <- function (.data, condition, time, lead_time = 0, lag_time = 0){
  condition <- enquo(condition)
  time <- enquo(time)
  filtered <- .data %>% slice(., 1:max(which(!!condition))) %>% 
    group_by(., grp = lag(cumsum(!!condition), default = 0)) %>% 
    filter(., (last(!!time) - !!time) <= lead_time & (last(!!time) - 
                                                        !!time) >= lag_time)
  return(filtered)
}

# this returns 23 rows of data. I would like to return everything except this data
event_df %>% filter_within_timeframe(event == "A", time_sec, 10, 0)

# final output should be 77 rows starting with...
# ~period,  ~time_sec,  ~event,
# 1,3,"B",
# 1,4,"B",
# 1,5,"B",

标签: r

解决方案


推荐阅读