# [R] How to apply apply?!

Philipp Pagel p.pagel at wzw.tum.de
Fri Aug 6 21:27:51 CEST 2010

```> 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?).

You don't use apply in this case - a simple multiplication and
variable assignment will do:

> require(tseries)
> foo <- get.hist.quote('^GDAXI')
> foo[1:10, ]
Open   High    Low  Close
1991-01-02 1375.4 1375.4 1359.1 1366.1
1991-01-03 1371.7 1374.7 1365.2 1366.7
1991-01-04 1375.4 1398.0 1375.4 1396.1
1991-01-07 1373.6 1373.6 1352.5 1358.2
1991-01-08 1350.4 1357.1 1345.5 1354.0
1991-01-09 1358.6 1380.8 1358.0 1375.2
1991-01-10 1367.9 1383.7 1363.1 1383.4
1991-01-11 1401.3 1406.4 1376.9 1382.3
1991-01-14 1354.5 1354.5 1327.8 1327.8
1991-01-15 1327.0 1330.3 1312.4 1325.6
> foo\$Close <- foo\$Close * 2
> foo\$Close <- foo\$Close * 2
> foo[1:10, ]
Open   High    Low  Close
1991-01-02 1375.4 1375.4 1359.1 2732.2
1991-01-03 1371.7 1374.7 1365.2 2733.4
1991-01-04 1375.4 1398.0 1375.4 2792.2
1991-01-07 1373.6 1373.6 1352.5 2716.4
1991-01-08 1350.4 1357.1 1345.5 2708.0
1991-01-09 1358.6 1380.8 1358.0 2750.4
1991-01-10 1367.9 1383.7 1363.1 2766.8
1991-01-11 1401.3 1406.4 1376.9 2764.6
1991-01-14 1354.5 1354.5 1327.8 2655.6
1991-01-15 1327.0 1330.3 1312.4 2651.2

> 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.

You can get the manual page of any R-command by either preceding it
by a question mark or giving the command as an argument to the help
function - specificly:

?apply
help(apply)

Especially the example section is useful for a jumpstart.
Here is an example of computing row means:

apply(foo, 1, mean)

Instead of 'mean' you can insert whatever function you'd like to apply.

cu
Philipp

--
Dr. Philipp Pagel
Lehrstuhl für Genomorientierte Bioinformatik
Technische Universität München
Wissenschaftszentrum Weihenstephan
Maximus-von-Imhof-Forum 3
85354 Freising, Germany
http://webclu.bio.wzw.tum.de/~pagel/

```