我有一个包含IF功能的自定义功能。当我在data.table中使用该函数时,我收到一条警告 "条件长度> 1,只使用第一个元素"。
我认为该函数可能会应用于列中的所有行,而不是根据需要一次应用于一行,但我不确定。
是否有人知道此警告出现的原因?
我的功能是:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>
int main()
{
time_t maxTime;
maxTime = INT_MAX;
char *strOfMaxTime = ctime(&maxTime);
printf("%s",strOfMaxTime);
return 0;
}
数据样本:
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
答案 0 :(得分:0)
根据评论中的建议,您可以使用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