[R] Trying to understand a function passed to lapply
Jim Lemon
drjimlemon at gmail.com
Tue Mar 31 04:59:20 CEST 2015
Hi John,
What happens is that you have passed two named arguments to your function
"myfun" along with the matrix "data". Because these arguments have
associated values ("delta", "SE"), these values are substituted into the
expression like this:
x["delta"]/x["SE"]
which is the return value of "myfun". If you just type in:
data["delta"]
data["SE"]
you will see the values that are successively selected for the calculation
in "myfun"
Jim
On Tue, Mar 31, 2015 at 12:48 PM, John Sorkin <jsorkin at grecc.umaryland.edu>
wrote:
> 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 ...{{dropped:16}}
More information about the R-help
mailing list