2020年12月23日星期三

How to use enquo with a vector element in r

Working on a custom function and I'm getting an error.. "Error: Quosures can only be unquoted within a quasiquotation context." Lots of similar q/a's but I'm not technically enough to interpret. All I can discern is that it is my attempt to call time_sec[event=='A'] via the custom function. Offending line is noted in the code below.

library(dplyr)    # the data  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)    # the function  filter_within_timeframe <- function(.data, condition, time, lead_time = 0, lag_time = 0){    condition <- enquo(condition)    time <- enquo(time)    filtered_lead <- c()    filtered_lag <- c()        if(lead_time > 0){    # filter lead events    filtered_lead <- .data %>%      slice(., 1:max(which(!!condition))) %>%      group_by(., grp =  lag(cumsum(!!condition), default = 0)) %>%      filter(.,(last(!!time) - !!time) <= lead_time & (last(!!time) - !!time) >= 0) %>%       select(-grp)    }      if(lag_time > 0){    #filter lag events    filtered_lag <- .data %>%      slice(min(which(!!condition)):nrow(.)) %>% # remove rows before first occurance      group_by(grp =  lead(rev(cumsum(rev(!!condition))), default = 0), period) %>%      filter((!!time - first(!!time[!!condition])) <= lag_time) # something in here doesn't work !!!!!!!!!!!!!    }      filtered <- rbind(filtered_lead, filtered_lag)    return(filtered)      }  

The call utilizing lead_time works as expected...

event_df %>% filter_within_timeframe(event == 'A', time_sec, 10, 0)  

...but the call to lag_time throws up the error..

event_df %>% filter_within_timeframe(event == 'A', time_sec, 0, 10)  
https://stackoverflow.com/questions/65433314/how-to-use-enquo-with-a-vector-element-in-r December 24, 2020 at 10:36AM

没有评论:

发表评论