using "keep" or "discard" from purrr to filter lists based on two conditions

Viewed 182

I am trying to use keep or discard from the purrr package to filter some list by two conditions. That is, with the data below I would like to filter the p.value when it is < 0.060 and > 0.050.

Applying the following obviously doesn't work keep(d, ~.x$p.value > 0.05 & ~.x$p.value < 0.10).

Data:

d <- list(ABMD = structure(list(statistic = c(`Dickey-Fuller` = -2.88823930907752), 
    parameter = c(`Lag order` = 3), alternative = "stationary", 
    p.value = 0.222153876057991, method = "Augmented Dickey-Fuller Test", 
    data.name = "Cl(.)"), class = "htest"), ATVI = structure(list(
    statistic = c(`Dickey-Fuller` = -2.86560166108736), parameter = c(`Lag order` = 3), 
    alternative = "stationary", p.value = 0.231115731952747, 
    method = "Augmented Dickey-Fuller Test", data.name = "Cl(.)"), class = "htest"), 
    ADBE = structure(list(statistic = c(`Dickey-Fuller` = -2.91292875187715), 
        parameter = c(`Lag order` = 3), alternative = "stationary", 
        p.value = 0.212379749850693, method = "Augmented Dickey-Fuller Test", 
        data.name = "Cl(.)"), class = "htest"), AMD = structure(list(
        statistic = c(`Dickey-Fuller` = -3.46654255102478), parameter = c(`Lag order` = 3), 
        alternative = "stationary", p.value = 0.0592779965240372, 
        method = "Augmented Dickey-Fuller Test", data.name = "Cl(.)"), class = "htest"), 
    AKAM = structure(list(statistic = c(`Dickey-Fuller` = -3.67846516682619), 
        parameter = c(`Lag order` = 3), alternative = "stationary", 
        p.value = 0.0380202892654308, method = "Augmented Dickey-Fuller Test", 
        data.name = "Cl(.)"), class = "htest"), ALXN = structure(list(
        statistic = c(`Dickey-Fuller` = -2.93110833009175), parameter = c(`Lag order` = 3), 
        alternative = "stationary", p.value = 0.205182767184581, 
        method = "Augmented Dickey-Fuller Test", data.name = "Cl(.)"), class = "htest"))
1 Answers

We don't need the double ~. It is anonymous function.

keep(d, ~.x$p.value > 0.05 & .x$p.value < 0.10)

It would be similar to Filter expression in base R

Filter(function(x) x$p.value > 0.05 & x$p.value < 0.10, d)

In the OP's code, it is doing double function

Filter(function(x) x$p.value > 0.05 & function(x) x$p.value < 0.10, d)
Related