user3294511
user3294511

Reputation: 51

Storing the results from a function

Hi I have made a basic function (I am newish to R).

analyse <- function(gene_set,probe_ids) {
    Xprobe_ids <- mapply(function(k) paste('X',k,sep=''), probe_ids)
    model_1_formula_str  = 'Status ~ Age + Sex + Source';
    model_1 <- glm(as.formula(model_1_formula_str), data = fcA, family = "binomial");
    model_2_formula_str = model_1_formula_str;
    for (next_id in probe_ids) {
        model_2_formula_str = paste(model_2_formula_str, ' + X',next_id,sep = '')
    }
    model_2 <- glm(as.formula(model_2_formula_str), data = fcA, family = "binomial");
    gene_pval = anova(model_2,model_1, test="Chisq")[2,5];
    probe_id_str <- paste(probe_ids,collapse=',');
    probe_num <- length(probe_ids);
    c(gene_set,gene_pval,probe_num,probe_id_str,);
}

And the problem occurs with,

for (next_id in probe_ids) {
    model_2_formula_str = paste(model_2_formula_str, ' + X',next_id,sep = '')
}

Essentially I want to analyse model 1 versus model 2, with model 2 changing for each different gene. However I am sending model 2 through a loop that simply changes model_2_formula_str over and over getting to the final gene and then carries out the analyses.

What I am wondering is, how would I get it to carry out the analyses store the results? Then moving onto the next gene do the same, and so on?

Thanks for any help!

Upvotes: 1

Views: 75

Answers (1)

Rorschach
Rorschach

Reputation: 32426

Should work to make a list of models with lapply

strings <- c()
for (next_id in probe_ids) {

    strings = c(strings, paste(model_2_formula_str, ' + X',next_id,sep = ''))

}

mods <- lapply(strings, FUN = function(x) {
    glm(as.formula(x), data = fcA, family = "binomial") })

Then just iterate over your list of models to make the comparisons you want

gene_pvals = lapply(mods, FUN = function(x) {
    anova(x, model_1, test="Chisq")[2,5]
})

Upvotes: 2

Related Questions