Goutham
Goutham

Reputation: 2859

Combine several data frames into a single data frame

I need to iterate over a vector and call a function. The result of this function is a data frame and I want to combine all the data frames returned by the function for each value in the vector into one data frame.

Consider the example below. I want to apply getDetails to each value of vec and combine the results.

vec = c(1,2)
getDetails = function(match){
  if (match == 1)
    return (data.frame(Player=c(1,2), Score = c(3,4)))
  else
    return (data.frame(Player=c(1,2), Score = c(7,8)))
}

What I would like returned is this:

  Player Score
1      1     3
2      2     4
3      1     7
4      2     8

I tried sapply but that returns a data frame of the same length as the vector (so each row is a data frame instead of a vector). Is there a simple solution to this?

Upvotes: 1

Views: 137

Answers (2)

hs3180
hs3180

Reputation: 198

try this in plyr,

ldply(vec, getDetails)

Upvotes: 1

Hong Ooi
Hong Ooi

Reputation: 57696

do.call(rbind, lapply(vec, getDetails))

Upvotes: 3

Related Questions