如何在R中使用try语句?

时间:2017-10-21 10:38:09

标签: r try-catch

所以我试图遍历一些数据并在我的代码中使用它们。我需要这个尝试的地方如下:

for (number in numbers) {
    CTV_volume <- CTV[ which(CTV$Key==number), ]$volume
    PTV_volume <- PTV[ which(PTV$Key==number), ]$volume
    ITV_volume <- ITV[ which(ITV$Key==numbers), ]$volume

    large_volume <- large_margin_vol_calc(radius_calc(CTV_volume), a_large, b_large)
    small_volume <- small_margin_vol_calc(radius_calc(CTV_volume), a_small, b_small) 
}

问题是最后两行(CTV_volumelarge_volume)中的small_volume计算取决于上面第一行(CTV_volume)的数据。但是,对于循环的每次迭代,有可能没有该特定键/数的CTV,而是我需要使用另一个,即ITV。但首先,我需要它首先使用CTV,如果存在,如果不存在,则需要ITV字。

如何在R中完成?

1 个答案:

答案 0 :(得分:1)

如果你找回一个空的矢量,即numeric(0),它在技术上不是错误。

因此,如果您使用tryCatch(),如下所示,结果将不会改变。

for (number in numbers) {
  CTV_volume <- CTV[ which(CTV$Key==number), ]$volume
  PTV_volume <- PTV[ which(PTV$Key==number), ]$volume
  ITV_volume <- ITV[ which(ITV$Key==numbers), ]$volume

  tryCatch({
    large_volume <- large_margin_vol_calc(radius_calc(CTV_volume), a_large, b_large)
    small_volume <- small_margin_vol_calc(radius_calc(CTV_volume), a_small, b_small)
    },
    error = function(e) {
      #what should be done in case of exeption?
      str(e) # prints structure of exeption
      large_volume <- large_margin_vol_calc(radius_calc(ITV_volume), a_large, b_large)
      small_volume <- small_margin_vol_calc(radius_calc(ITV_volume), a_small, b_small) 
    }
  )
}

相反,您可能要做的是检查CTV_volume是否具有预期长度。

for (number in numbers) {
  CTV_volume <- CTV[ which(CTV$Key==number), ]$volume
  PTV_volume <- PTV[ which(PTV$Key==number), ]$volume
  ITV_volume <- ITV[ which(ITV$Key==numbers), ]$volume

  if (length(CTV_volume) > 0) {
    large_volume <- large_margin_vol_calc(radius_calc(CTV_volume), a_large, b_large)
    small_volume <- small_margin_vol_calc(radius_calc(CTV_volume), a_small, b_small) 
  } else {
    large_volume <- large_margin_vol_calc(radius_calc(ITV_volume), a_large, b_large)
    small_volume <- small_margin_vol_calc(radius_calc(ITV_volume), a_small, b_small) 
  }
}