I'm running a large number of meta-analyses with metafor. To get an overview of the results, I wanted to put together vectors containing the main estimates (to combine them in a dataframe later on). Yet, for some of these calculations, I do not have enough primary studies yet, so R will not be able to create a model for this particular domain. Hence, I will get an error message when I try to create a vector at the end.
library(metafor)
r1<-c(NA,NA)
n1<-c(NA,NA)
data1<-data.frame(r1,n1)
escalc1<-escalc(measure="COR", ri=r1,ni=n1, data = data1, method=REML)
rma1<-rma(yi,vi, data=escalc1)
#note the program will not be able to calculate rma1, because k = 0.
r2<-c(.3,.2)
n2<-c(100,200)
data2<-data.frame(r2,n2)
escalc2<-escalc(measure="COR", ri=r2,ni=n2, data = data2, method=REML)
rma2<-rma(yi,vi, data=escalc2)
#it will create an object for rma2 though
estimates<-c(rma1$beta, rma2$beta)
#as rma2 exists but rma1 doesn't, R will no let me create a vector here
Is there a way to tell R to check if the object exists first and to put in NAs for all cases where no object has been created yet? Specifically, I want R to replace rma1$beta (which does not exist) with NA in the last line of code. Is that possible?
You can use tryCatch
to tell R what to do as an alternative if an error occurs, e.g.,
library(metafor)
r1<-c(NA,NA)
n1<-c(NA,NA)
data1<-data.frame(r1,n1)
escalc1<-escalc(measure="COR", ri=r1,ni=n1, data = data1)
e1 <- tryCatch({
rma1<-rma(yi,vi, data=escalc1);
rma1$beta}, error = function(e) NA)
r2<-c(.3,.2)
n2<-c(100,200)
data2<-data.frame(r2,n2)
escalc2<-escalc(measure="COR", ri=r2,ni=n2, data = data2)
e2 <- tryCatch({
rma2<-rma(yi,vi, data=escalc2);
rma2$beta}, error = function(e) NA)
estimates<-c(e1, e2)
#[1] NA 0.2356358