Search code examples
rmathdataframearithmetic-expressions

Extracting values from function output based on being greater than or less than


I have created multiple functions using this code:

getT <- function(df, ID, Number){
  df %>%
    group_by(ID, Number) %>% 
    mutate( Distance = finish - begin) %>% 
    select(-begin,-finish,-symbols) %>%
    nest() %>% 
    mutate( data = map( data, ~ filter(.x, Distance == max(Distance)))) %>% 
    unnest()
}

getallT <- as.data.frame(getT(df))

getTID <- function(df, ID) {
  df1 <- getallT(df)
  subset(x = getallT, subset = (ID))
}`    

Which gives me an output like this:

ID     Number     Time     Distance
33         1      2.00         870
33         2      1.98         859
33         3      0.82         305
33         4      2.02         651
33         5      2.53         502

I am wondering if there is a way to extract the Time values based on how low or high the value is? In the case of above, I would like to create a function that could extract the values that were above 2.00 so it would have an output like this instead:

ID     Number     Time     Distance
33         4      2.02         651
33         5      2.53         502

Eventually, I would like to create a different function to extract the values that are below 1.00 and then go further by creating another different function for the combination of the two but I think I can do that once I know how to do the first part! Any response is much appreciated.


Solution

  • Here's your data frame:

    df <- data.frame(ID=rep(33,5),
                     Number=1:5,
                     Time=c(2.00,1.98,0.82,2.02,2.53),
                     Distance=c(870,859,305,651,502))
    

    You can keep values <=1 and >=2 with filter, between and !

    df <- df %>% filter(!between(Time,1,2))
    
      ID Number Time Distance
    1 33      3 0.82      305
    2 33      4 2.02      651
    3 33      5 2.53      502