我正在尝试在R中使用knn()并且当预测变量是数值变量时它可以正常工作但是当我使用分类变量作为预测变量时knn()失败并出现以下错误:
Error in knn(train = data.frame(csa.training), test = data.frame(csa.test), :
NA/NaN/Inf in foreign function call (arg 6)
In addition: Warning messages:
1: In knn(train = data.frame(csa.training), test = data.frame(csa.test), :
NAs introduced by coercion
2: In knn(train = data.frame(csa.training), test = data.frame(csa.test), :
NAs introduced by coercion
knn()是否设计为接受分类预测因子或根本不接受?
我的函数调用是:
csa.training<-csa_clean[csa_clean$RN_ind==1,c("Age.at.Surgery.","Sex.")]
csa_pred<-knn(train=data.frame(csa.training),test=data.frame(csa.test),cl=csa.trainlabels,k=3)
如果我删除性别。分类变量问题消失了。性。列似乎很干净,没有NAs等。
summary(csa_clean$Sex.)
Female Male
119 188
数据:
csa.training[1,]
Age.at.Surgery. Grade. Sex.
1 38 2 Female
> csa.test[1,]
Age.at.Surgery. Grade. Sex.
3 24 2 Female
csa.trainlabels[1]
[1] Alive
Levels: Alive Dead