【问题标题】:R if statement to return NULL when data not availableR if 语句在数据不可用时返回 NULL
【发布时间】:2018-09-15 08:23:44
【问题描述】:

我正在尝试创建一个 if 语句,以便当 filter(OD > threshold_1)%>% 未找到或在 df 中不存在时,它返回“NULL”而不是当前返回的内容...

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))
}

返回:

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

因此,如果return_value_1 不可用,我希望它返回NULL,例如:

time_hdt_upper OD_hdt_upper

  NULL            NULL

换句话说,我想要:#if return_value_1[1,1] equals NA set return_value_1[1,1] and return_value_1[1,2] to "NULL"

我尝试了以下组合:

  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))
}

返回错误:

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

【问题讨论】:

    标签: r if-statement null


    【解决方案1】:

    让你的 if 语句查看 return_value:

    if (nrow(return_value) == 0) {
        return (NULL)
    } else {
        return(return_value)
    }
    

    【讨论】:

      猜你喜欢
      • 2013-07-05
      • 2018-01-08
      • 2022-09-29
      • 2020-12-15
      • 2020-05-16
      • 2016-02-12
      • 1970-01-01
      • 1970-01-01
      • 2013-09-09
      相关资源
      最近更新 更多