fredrik
fredrik

Reputation: 11

R - Apply function on every row, with data from the row

Is there a faster way to do this:

for (i in 1:nrow(dataframe))
{
dataframe$results <- with(dataframe, myownfunction(column1[i],
  column2[i], column3[i], column4[i], column5[i], column6[i])
}

myownfunction finds implied volatility using uniroot(), but when uniroot does not find a solution it stops (usually because there some faults in the data), and the loop stops. Is there a way to make the function just output NA if it gets an error from uniroot and continue with the next row?

regards.

Upvotes: 1

Views: 1347

Answers (3)

Chris Neff
Chris Neff

Reputation: 225

You seem to have to questions:

1) Returning a value if failure happens. As posted already, look at failwith in the plyr package. It does exactly this.

2) Speed up the for loop. Have you tried using mapply? It is a multivariate apply that applies a function to the each element of each argument simultaneously. So

mapply(myfunc, column1, column2, column3, column4)

(along with modifying myfunc to use failwith) would do the sort of thing you are looking for.

The plyr version of mapply is mdply if you prefer.

Upvotes: 0

NAR
NAR

Reputation: 1

Got this from another forum, I like it more than the previous options:

R> M <- matrix(1:6, nrow=3, byrow=TRUE)

R> M

         [,1] [,2]
    [1,]    1    2

    [2,]    3    4

    [3,]    5    6
    R> apply(M, 1, function(x) 2*x[1]+x[2])

    [1]  4 10 16

Upvotes: -1

IRTFM
IRTFM

Reputation: 263342

Part1: It's very likely that you could succeed with:

ave( dataframe[, c("column1", column2", column3", "column4", "column5", "column6")], myownfunction)

Part2: If you modified the function to test for failure with try and returned NA when it fails you can fill in the missing data in the result properly.

Upvotes: 2

Related Questions