在 data.table 中使用 if 函数的警告消息
Warning message using if function in data.table
我有一个包含函数 IF 的自定义函数。当我在 data.table 中使用该函数时,我收到一条警告说
"the condition has length > 1 and only the first element will be used".
我认为该函数可以应用于列中的所有行,而不是根据需要一次应用于一行,但我不确定。
有人知道为什么会出现这个警告吗?
我的函数是:
HeatIndex<-function(TempC,RH)
{
TFarheit= TempC * 1.8 + 32
if( TFarheit <80 ) {
Te=TempC /15
HI = Te/15
} else {
TA=TempC /11
HI = TA/125
}
HI= (HI - 32) / 1.8
return(HI )
}
数据样本:
HeatINDEX=data.table(Ave_MeanRH=c(0,100), Ave_MeanT=c(10,20)) #create data.table
并将函数应用于数据
HeatINDEX[,HI:=HeatIndex(HeatINDEX$Ave_MeanT, HeatINDEX$Ave_MeanRH)]
正如评论中所建议的,您可以使用 ifelse()
向量化您的热指数函数。这肯定比逐行计算更快,这是评论中建议的另一种解决方案。
# Vectorized version of function:
computeHI = function(T_cel, RH) {
T_far = T_cel * 1.8 + 32
HI = ifelse(test=T_far < 80,
yes=(T_cel / 15) / 15,
no=(T_cel / 11) / 125)
HI = (HI - 32) / 1.8
return(HI)
}
HeatINDEX[,HI:=HeatIndex(Ave_MeanT, Ave_MeanRH), by=seq(2)]
HeatINDEX[,vectorized_HI:=computeHI(Ave_MeanT, Ave_MeanRH)]
HeatINDEX
# Ave_MeanRH Ave_MeanT HI vectorized_HI
# 1: 0 10 -17.75309 -17.75309
# 2: 100 20 -17.72840 -17.72840
我有一个包含函数 IF 的自定义函数。当我在 data.table 中使用该函数时,我收到一条警告说 "the condition has length > 1 and only the first element will be used".
我认为该函数可以应用于列中的所有行,而不是根据需要一次应用于一行,但我不确定。
有人知道为什么会出现这个警告吗?
我的函数是:
HeatIndex<-function(TempC,RH)
{
TFarheit= TempC * 1.8 + 32
if( TFarheit <80 ) {
Te=TempC /15
HI = Te/15
} else {
TA=TempC /11
HI = TA/125
}
HI= (HI - 32) / 1.8
return(HI )
}
数据样本:
HeatINDEX=data.table(Ave_MeanRH=c(0,100), Ave_MeanT=c(10,20)) #create data.table
并将函数应用于数据
HeatINDEX[,HI:=HeatIndex(HeatINDEX$Ave_MeanT, HeatINDEX$Ave_MeanRH)]
正如评论中所建议的,您可以使用 ifelse()
向量化您的热指数函数。这肯定比逐行计算更快,这是评论中建议的另一种解决方案。
# Vectorized version of function:
computeHI = function(T_cel, RH) {
T_far = T_cel * 1.8 + 32
HI = ifelse(test=T_far < 80,
yes=(T_cel / 15) / 15,
no=(T_cel / 11) / 125)
HI = (HI - 32) / 1.8
return(HI)
}
HeatINDEX[,HI:=HeatIndex(Ave_MeanT, Ave_MeanRH), by=seq(2)]
HeatINDEX[,vectorized_HI:=computeHI(Ave_MeanT, Ave_MeanRH)]
HeatINDEX
# Ave_MeanRH Ave_MeanT HI vectorized_HI
# 1: 0 10 -17.75309 -17.75309
# 2: 100 20 -17.72840 -17.72840