Question: How to apply a function to a list and get results as a list in R?
0
gravatar for jzhou
3.7 years ago by
jzhou20
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 <- ifelseis.na(s1),next,(round(1 - pchisq(s1$chisq, length(s1$n) - 1),3)))[[1]]

Thanks so much!

survival rna-seq tcga R • 1.6k views
ADD COMMENTlink modified 3.7 years ago by lakhujanivijay5.0k • written 3.7 years ago by jzhou20
1

Have a look at apply().

ADD REPLYlink written 3.7 years ago by Jean-Karim Heriche22k

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

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

ADD REPLYlink written 3.7 years ago by Giovanni M Dall'Olio27k
3
gravatar for lakhujanivijay
3.7 years ago by
lakhujanivijay5.0k
India
lakhujanivijay5.0k wrote:

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

apply()

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

Usage:

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

Arguments:

   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()

 ‘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 3.7 years ago • written 3.7 years ago by lakhujanivijay5.0k
Please log in to add an answer.

Help
Access

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