用户定义函数出错

时间:2022-09-30 20:26:54

I have a user defined function that I am using on the following data set:

我有一个用户定义的函数,我在以下数据集上使用:

Pos      
A
B
C
A
C
B

I created the following function to add a variable to the data set.

我创建了以下函数来向数据集添加变量。

Predict <- function(Uncontested.REB.per.game, STL.per.game, BLK.per.game, Opp.FGA.at.rim.per.game, PTS.per.game, Passes.per.game, log.Points.created.by.assist.per.game, sqrt.Drives.Per.Game, Pos){
if (Pos=="A"){
Pred = 1}
  else if(Pos=="B"){
Pred=4}
else if(Pos=="C"){
Pred=5
}
}

When I use the following command(s): Data <- transform(Data, Pred = Predict(Pos)

当我使用以下命令时:数据< - transform(Data,Pred = Predict(Pos))

I get the error "the condition has length > 1 and only the first element will be used". I think that it has something to do with using an "if" statement on that I want to apply to each row instead of just one element, so I also tried a variation of the code above:

我得到错误“条件长度> 1,只使用第一个元素”。我认为它与使用“if”语句有关,我想要应用于每一行而不是一个元素,所以我也尝试了上面代码的变体:

Predict <- function(Pos){
if (Pos=="B" && Pos!="A"){
Pred = 1}
  else if(Pos=="A"&&Pos!="B"){
Pred=4}
else if(Pos=="C" && Pos!="A"){
Pred=5
 }
 }

However, this just put the same value for Pred in all of the rows despite the different positions.

然而,尽管位置不同,这只是在所有行中为Pred设置了相同的值。

1 个解决方案

#1


You should vectorize your function. For example change you conditions statements using ifelse :

你应该对你的功能进行矢量化。例如,使用ifelse更改条件语句:

Predict <- function(Pos){   
   Pred <- ifelse(Pos=="A",1,ifelse(Pos=="B",4,5))
   Pred
}

#1


You should vectorize your function. For example change you conditions statements using ifelse :

你应该对你的功能进行矢量化。例如,使用ifelse更改条件语句:

Predict <- function(Pos){   
   Pred <- ifelse(Pos=="A",1,ifelse(Pos=="B",4,5))
   Pred
}