[R] using apply to a data frame

Bert Gunter bgunter.4567 at gmail.com
Thu Apr 7 22:51:06 CEST 2016


-- Bert
Bert Gunter

On Thu, Apr 7, 2016 at 1:25 PM, John Sorkin <JSorkin at grecc.umaryland.edu> wrote:
> ‪‪I would like to apply a function, fract, to the columns of a
> dataframe. I tried the following
> apply(data5NonEventEpochs,2,fract)
> but, no surprise it did not work as apply works on matrices not data
> frames.

That is false! From ?apply:

"If X is not an array but an object of a class with a non-null dim
value (such as a data frame), apply attempts to coerce it to an array
via as.matrix if it is two-dimensional (e.g., a data frame) or via

Your apply() call would not have worked with a matrix either, as your
syntax was wrong.  Here is a corrected example:

> X <- data.frame(a=1:5,b=6:10)

> apply(X,2,function(x)mean(sqrt(x)))
       a        b
1.676466 2.817189

 How can I apply a fuction to the columns of a data frame? (I
> can't covert data5NonEventsEpochs to a matrix as it contains character
> data).
> Thank you,
> John
> John David Sorkin M.D., Ph.D.
> Professor of Medicine
> Chief, Biostatistics and Informatics
> University of Maryland School of Medicine Division of Gerontology and
> Geriatric Medicine
> Baltimore VA Medical Center
> 10 North Greene Street
> GRECC (BT/18/GR)
> Baltimore, MD 21201-1524
> (Phone) 410-605-7119
> (Fax) 410-605-7913 (Please call phone number above prior to faxing)
> Confidentiality Statement:
> This email message, including any attachments, is for ...{{dropped:12}}

More information about the R-help mailing list