cbvxsr
cbvxsr

Reputation: 13

R returns partial (incomplete) results from function

I try to compare models in a meta-analysis that I calculated using the package metafor (rma.mv- or rma - function). I try to write a function that extracts specific values (here: just beta and the standard error) from i models and adds them to a data frame.

My problem is that the model results do not end up as data or as a data frame. The header repeats every row. When I turn the results into an object and try to call it, R just returns NULL.

*Edit. I missed the return. Now it is just returns one row!

Any advice is welcome. Thanks,

#data1
effectsize1 <- c(0.25, 0.15, 0.36)
variance1 <- c(0.05, 0.026, 0.041)
#data2
effectsize2 <- c(0.52, 0.16, 0.27)
variance2 <- c(0.01, 0.09, 0.063)

#model
library(metafor)
model1 <- rma(effectsize1, variance1)
model2 <- rma(effectsize2, variance2)

# function
extract_results <- function(...) {
  x <- list(...)
       for (i in x){
       b <- as.numeric(i$beta)
       se <- as.numeric(i$se)
       df <- data.frame(b, se)
       }
    return(df)
    }

#results
          b        se
1 0.2359601 0.1098624
          b        se
1 0.4290981 0.1126032

res <- extract_results(model1, model2)
res
NULL

*edit

> res <- extract_results(model1, model2)
> res
          b        se
1 0.2359601 0.1098624

Upvotes: 0

Views: 39

Answers (1)

akrun
akrun

Reputation: 887571

The return should be outside the for loop i.e. combining the output from each of the iterations with rbind after initializing a 0 row dataset ('df')

extract_results <- function(...) {
  x <- list(...)
  df <- data.frame(b=numeric(), se = numeric())
       for (i in x){
       b <- as.numeric(i$beta)
       se <- as.numeric(i$se)
       df <- rbind(df, data.frame(b, se))
       
       }
       return(df)
    }

-testing

> res <- extract_results(model1, model2)
> res
          b        se
1 0.2359601 0.1098624
2 0.4290981 0.1126032

Upvotes: 1

Related Questions