-2

I have a vector of matchIds and a function that returns the players who played in that match as a vector (say getPlayersFromMatchId is the function). Now my question is, what is the most idiomatic way of iterating over the matchIds, extracting the player info and building a data frame where each row corresponds to the players who played in that match? Here's a simple for loop that does the trick

for (match in matchIds){
    players = getPlayersFromMatchId(match)
    Add players to a dataframe
}

I can iterate over the matchIds but how do I build the data frame with each value returned by the function?

Goutham
  • 2,759
  • 9
  • 30
  • 36
  • 1
    You should avoid adding rows to a data.frame one-by-one. That's generally a terrible idea. Is there a reason `getPlayersFromMatchId` isn't vectorized (vector in, vector out)? You could wrap it in `Vectorize` or do a simple `sapply()` to get all the values you need at once. Your question would be much easier to answer if you actually included a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input, and desired output and code that is actually runnable. – MrFlick Sep 06 '14 at 03:22
  • Its extracting the data from a website depending on the matchId. I have to combine the player information for all the matches at some point. – Goutham Sep 06 '14 at 03:24
  • 1
    Well your description is too vague to be precisely answered. But the general idea is fill vectors of data you want to store as columns, then combine in a data frame when done. – MrFlick Sep 06 '14 at 03:26
  • sapply did the trick, thanks. Sorry about the vague description. – Goutham Sep 06 '14 at 08:03

1 Answers1

0

If you must do it your way, following may help:

dd = data.frame(players = list())
for (match in matchIds){
    dd$players[nrow(dd)+1] = getPlayersFromMatchId(match)
    Add players to a dataframe
}
dd$players
rnso
  • 23,686
  • 25
  • 112
  • 234