jeudi 5 avril 2018

R if statement to return NULL when data not available

I am trying to create an if statement so that when filter(OD > threshold_1)%>% is not found or does not exist in dfit returns "NULL" instead of what is being returned currently...

library(dplyr)

find_time = function(df, threshold_1, threshold_2, ODf){
    return_value_1 = df %>%
    arrange(time) %>%
    filter(OD > threshold_1) %>%
    slice_(1)
    colnames(return_value_1)[1] <- "time_hdt_upper"
    colnames(return_value_1)[2] <- "OD_hdt_upper"

    return(data.frame(return_value_1))
}

returns:

[1] time_hdt_upper OD_hdt_upper  
<0 rows> (or 0-length row.names

Thus I would like it to return NULL if return_value_1 is not available, as such:

time_hdt_upper OD_hdt_upper

  NULL            NULL

In other words, I want: #if return_value_1[1,1] equals NA set return_value_1[1,1] and return_value_1[1,2] to "NULL"

I have tried a combination of:

  find_time = function(df, threshold_1){
    return_value_1 = df %>%
    arrange(time) %>%
    filter(OD > threshold_1) %>%
    slice_(1)
    colnames(return_value_1)[1] <- "time_hdt_upper"
    colnames(return_value_1)[2] <- "OD_hdt_upper"

    if(OD %>% threshold_1 %in% df) {return("no threshold")}

    return(data.frame(return_value_1))
}

returns error:

Error in eval(lhs, parent, parent) : object 'OD' not found
Called from: eval(lhs, parent, parent)

Aucun commentaire:

Enregistrer un commentaire