所以我试图遍历一些数据并在我的代码中使用它们。我需要这个尝试的地方如下:
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_volume
和small_volume
)的计算取决于上面第一行 ( CTV_volume
) 的数据。但是,对于循环的每次迭代,都有可能没有该特定键/号码的 CTV,而我需要使用另一个,即 ITV。但首先,我需要它首先使用 CTV(如果存在),如果没有,则使用 ITV 词。
这在 R 中是如何实现的?
如果您返回一个空向量,即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)
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句