[R] Trying to understand a function passed to lapply

John Sorkin jsorkin at grecc.umaryland.edu
Tue Mar 31 03:48:45 CEST 2015


Colleagues,
I am trying to understand the syntax of a function passed to apply. The code below generates a matrix, and passes the matrix to a function that is called by apply. I don't understand the syntax of the function. In some way the function computes data[,"delta"]/data[,"SE"]. I can't understand how the body of the function, x[c1]/x[c2] refers to the columns "data" and "SE" of the matrix data. Can someone help me understand the syntax? 
Thank you,
John

myfun <- function(x, c1, c2) x[c1]/x[c2]
apply(data,1,myfun,c1="delta",c2="SE")

CODE:

data<-matrix(data=c(-0.70 ,-0.90, -0.50, 20, 20,
                    -0.30 ,-0.43, -0.17, 43, 43,
                    -0.50 ,-1.05,  0.05, 16, 18,
                     0.00 ,-0.21,  0.21, 22, 23,
                    -1.30 ,-1.48, -1.12, 28, 32,
                    -0.90 ,-1.01, -0.79, 18, 15,
                    -0.20 ,-0.47,  0.07, 39, 39,
                    -0.30 ,-0.83,  0.23, 27, 27),
                     nrow=8,ncol=5,byrow=TRUE)
dimnames(data) <- list(NULL,c("delta","low","high","n1","n2"))
data
CI <- data[,"high"]-data[,"low"]
data <- cbind(data,CI)
data
data <- cbind(data,SE=data[,"CI"]/(4*1.96))
data
data <- cbind(data,SD=data[,"SE"]*sqrt(data[,"n1"]+data[,"n2"]))
data
myfun <- function(x, c1, c2) x[c1]/x[c2]
apply(data,1,myfun,c1="delta",c2="SE")

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 the sole use of the intended recipient(s) and may contain confidential and privileged information. Any unauthorized use, disclosure or distribution is prohibited. If you are not the intended recipient, please contact the sender by reply email and destroy all copies of the original message. 


More information about the R-help mailing list