2017-10-21 247 views
0

所以我想循环一些数据并在我的代码中使用它们。在这里我需要这个东西试试看的位置是在以下几点:如何在R中使用try语句?

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_volume计算在最后两行(large_volumesmall_volume)取决于数据从第一线以上(CTV_volume)。但是,对于循环的每一次迭代,都有可能没有该特定键/数字的CTV,而是需要使用另一个,即ITV。但首先我需要它首先使用CTV,如果不存在的话,那么ITV词。

这是如何在R中完成的?

+0

这很容易。尝试“如果”。此外,由于你循环,你需要将你的值保存在列表或向量中。 – Alice

+0

但是我可以使用if语句有错误吗?例如,当我运行代码并运行到CTV不存在的地方时,我会得到“value”数值(0)而不是数字。人们可以在这样的“价值”上使用if语句吗? –

+0

你可以测试一个对象的长度为0 – hrbrmstr

回答

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