Reputation: 339
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.
Upvotes: 1
Views: 45
Reputation: 121568
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
}
Upvotes: 1