Question: How to apply a function to a list and get results as a list in R?
gravatar for jzhou
4.0 years ago by
USA, California
jzhou20 wrote:

I'd like to run the below code for my table, but instead of defining "ind_gene" as a single row name and running everything based on that, I want to run mass survival analysis and extract the p-value for every gene listed in rownames(z_rna), and have R return the results to me as a list. Could anyone please point me towards a method to do this?

# pick your gene of interest
ind_gene <- which(rownames(z_rna) == "TP53")

# run survival analysis
s <- survfit(Surv(as.numeric(as.character(all_clin$new_death))[ind_clin],all_clin$death_event[ind_clin])~event_rna[ind_gene,ind_tum])
s1 <- tryCatch(survdiff(Surv(as.numeric(as.character(all_clin$new_death))[ind_clin],all_clin$death_event[ind_clin])~event_rna[ind_gene,ind_tum]), error = function(e) return(NA))

# extract the p.value
pv <-,next,(round(1 - pchisq(s1$chisq, length(s1$n) - 1),3)))[[1]]

Thanks so much!

survival rna-seq tcga R • 1.7k views
ADD COMMENTlink modified 4.0 years ago by lakhujanivijay5.2k • written 4.0 years ago by jzhou20

Have a look at apply().

ADD REPLYlink written 4.0 years ago by Jean-Karim Heriche23k

There is a missing parenthesis in the last row, between ifelse and

My two cents is to do this on tables instead of lists.

ADD REPLYlink written 4.0 years ago by Giovanni M Dall'Olio27k
gravatar for lakhujanivijay
4.0 years ago by
lakhujanivijay5.2k wrote:

You can use either apply() or lapply() functions. Here is the description:


Returns a vector or array or list of values obtained by applying a function to margins of an array or matrix.


 apply(X, MARGIN, FUN, ...)


   X: an array, including a matrix.

MARGIN: a vector giving the subscripts which the function will be applied over. E.g., for a matrix ‘1’ indicates rows, ‘2’ indicates columns, ‘c(1, 2)’ indicates rows and columns. Where ‘X’ has named dimnames, it can be a character vector selecting dimension names.

 FUN: the function to be applied: see ‘Details’.  In the case of
      functions like ‘+’, ‘%*%’, etc., the function name must be
      backquoted or quoted.

 ...: optional arguments to ‘FUN’.


 ‘lapply’ returns a list of the same length as ‘X’, each element of
 which is the result of applying ‘FUN’ to the corresponding element
 of ‘X’.

Here is a fantastic tutorial

PS: in your case lapply() is suitable because you mentioned that the output should be a list.

ADD COMMENTlink modified 4.0 years ago • written 4.0 years ago by lakhujanivijay5.2k
Please log in to add an answer.


Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 2090 users visited in the last hour