[R] How to apply apply?!

Erik Iverson eriki at ccbr.umn.edu
Fri Aug 6 21:16:04 CEST 2010



Raghuraman Ramachandran wrote:
> guRus
> 
> I have say a dataframe, d and I wish to do the following:
> 
> 1) For each row, I want to take one particular value of the row and multiply
> it by 2. How do I do it. Say the data frame is as below:
>    OPEN HIGH LOW CLOSE 1931.2 1931.2 1931.2 1931.2 0 0 0 999.05 0 0 0 1052.5
> 0 0 0 987.8 0 0 0 925.6 0 0 0 866 0 0 0 1400.2 0 0 0 754.5 0 0 0 702.6 0 0 0
> 653.25 0 0 0 348 0 0 0 801 866.55 866.55 866.55 866.55 783.1 783.1 742.25
> 742.25 575 575 575 575 0 0 0 493 470 470 420 425 355 360 343 360 312.05
> 312.05 274 280.85 257.35 257.35 197 198.75 182 185.95 137 150.75 120.25 129
> 90.7 101.25 91.85 91.85 57 66.6

Much easier to give us the ?dput output so we can construct this!

> 
> How do I multiply only the close of every row using the 'apply' function?
> And once multiplied how do I obtain a new table that also contains the new
> 2*CLOSE column (without cbind?).

Guessing here... but why do you want to use apply? Isn't

df$new.col <- df$CLOSE * 2

what you want?

> 
> 2) Also, how do I run a generic function per row. Say for example I want to
> calculate the Implied Volatility for each row of this data frame ( using the
> RMterics package). How do I do that please using the apply function? I am
> focusing on apply because I like the vectorisation concept in R and I do not
> want to use a for loop etc.

Simply read ?apply to see examples.  Apply works on matrices, not 
data.frames, so if you give it a data.frame, it will be coerced into a 
matrix.

apply(your.data, 1, your.function)



More information about the R-help mailing list