简体   繁体   中英

Error with a User Defined Function

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)

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:

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM