cainesap
cainesap

Reputation: 110

R: build data frame in user defined function

I've run into a problem in defining a function in R. I'm trying to convert the contents of a for loop into a function, so that I can lapply the function to a list, (and in turn mclapply using the multicore package)

I need to build a data frame row by row, taking one text and one numerical value at a time from the function. I understand from a previous post that I must return the values somehow, because of R's pass-and-copy rather than pass-by-reference scheme (see: How to add a column in the data frame within a function

Here's a simplified version of what I'm doing:

letters <- c('aa', 'bb', 'cc', 'aa', 'bb', 'dd', 'cc', 'dd', 'ee', 'ee')
numbers <- 1:10
madeup <- data.frame(letters, numbers)
output <- data.frame()

functest <- function(x) {
    subtest <- subset(madeup, letters==x)
    if (nrow(subtest==2)){
        calc <- subtest$numbers[2] - subtest$numbers[1]
        ...WHAT GOES HERE?...
    }
}

Anyone know what I should do to return x and calc so that I can then rbind these two values each into a new row of the output data frame?

If I can copy these two values from the function, I'm imagining the execution command will look something like ---

output <- rbind(output, [mc]lapply(letters, functest))

--- but am happy to be corrected on this!

Upvotes: 2

Views: 11033

Answers (1)

Nick Sabbe
Nick Sabbe

Reputation: 11956

rbinding data.frames is very slow in my experience, but anyway: replace your placeholder with return(data.frame(x,calc)).

After changing the function, probably the easiest way to get them all into one data.fameis through:

output<-do.call(rbind, lapply(letters, functest))

Upvotes: 2

Related Questions