mercredi 6 avril 2016

How to conditionally call a function for each row in R?

I am trying to call a function that provides a value for specific data elements in a table.

A data table (gameData) might be:

            Date TeamA TeamB TeamAScore TeamBScore
    1 2016-03-06   NYC   HOU         67         76
    2 2016-02-14   BOS   SEA        NaN        NaN
    3 2016-01-30   LAS   DAL         63         74

I would like to populate the TeamAScore with the return of a function if it is NaN. I tried a function like the following:

gameData$TeamAScore <- ifelse(
  is.nan(gameData$TeamAScore),
  getTeamAScore(gameData$TeamA,gameData$TeamB,gameDate=gameData$Date),
  gameData$TeamAScore
)

When I run this, I get a an error like the following:

Error in Ops.factor(teamdata$Team, TeamA) : level sets of factors are different

It seems to be sending all of the TeamA's with the function call instead of only the value for that row.

Aucun commentaire:

Enregistrer un commentaire