user7905871
user7905871

Reputation:

How to use apply function with list of functions with multiple argument in r?

I repeat more than 10 functions, three or more times for each function in R!! it is very confusing and wasting my time. I understand the idea of apply function but very basic and need a help with this issue.

I have these functions (part of my whole functions):

sel_1 <- lower.tri(fam1)  # selector for lower triangular matrix
     if (check.pars & (any(fam1 != 0) | any(!is.na(par11)))) {
          BiCopCheck(fam1[sel_1], par11[sel_1], par21[sel_1], call = match.call())
     }
     sel_2 <- lower.tri(fam2)
     if (check.pars & (any(fam2 != 0) | any(!is.na(par11)))) {
          BiCopCheck(fam2[sel_2], par12[sel_2], par22[sel_2], call = match.call())
     }
     sel_3 <- lower.tri(fam3)
     if (check.pars & (any(fam3 != 0) | any(!is.na(par13)))) {
          BiCopCheck(fam3[sel_3], par13[sel_3], par23[sel_3], call = match.call())
     }


     MixRVM1 <- list(Matrix = Matrix,
          fam1 = fam1,
          par11 = par11,
          par21 = par21,
          names = names,
          MaxMat = MaxMat,
          CondDistr = CondDistr)
     MixRVM12 <- list(Matrix = Matrix,
          fam2 = fam2,
          par12 = par12,
          par22 = par22,
          names = names,
          MaxMat = MaxMat,
          CondDistr = CondDistr)

Is there an easy way to repeat these functions?

Upvotes: 0

Views: 78

Answers (1)

moodymudskipper
moodymudskipper

Reputation: 47320

It's hard without the data, but by following these principles you should be able to improve your code:

if you don't already have your fam and par variables in a neat format (which you should if you have control over it):

fam_variables <- grep("fam[0-9]",ls(),value=TRUE)
fam_variables <- sel_variables[order(sapply(fam_variables,function(x){as.numeric(substr(x,4,nchar(x)))}))]
fam <- lapply(fam_variables,get) # assuming there's no missing sel variable from 1 to n!
par_list <- list(list(par11,par12,par13),list(par21,par22,par23))

Then you can use apply functions over these lists:

sel <- lapply(fam,lower.tri)
sapply(1:3,function(i){BiCopCheck(fam[[i]][sel[[i]]], par_list[[1]][[i]][sel[[i]]], par_list[[2]][[i]][sel[[i]]], call = match.call())})

MixRVM <- list() # we create a list, and we'll keep the same structure for every item (so the name will be the same among elements)
for (i in 1:2){
  MixRVM[[i]] <- list(Matrix = Matrix,
                          fam = fam[[i]],
                          par1i = par_list[[1]][[i]],
                          par2i = par_list[[2]][[i]],
                          names = names,
                          MaxMat = MaxMat,
                          CondDistr = CondDistr)
}

Upvotes: 2

Related Questions