How to apply a function to a list and get results as a list in R?
1
0
Entering edit mode
7.6 years ago
jzhou ▴ 20

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!

RNA-Seq survival tcga R • 3.1k views
ADD COMMENT
1
Entering edit mode

Have a look at apply().

ADD REPLY
0
Entering edit mode

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 REPLY
3
Entering edit mode
7.6 years ago

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 COMMENT

Login before adding your answer.

Traffic: 2025 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6