如何在r中使用带有多个参数的函数列表的apply函数?

时间:2017-07-03 12:46:09

标签: r

我为R中的每个功能重复超过10个功能,三次或更多次!这是非常混乱和浪费我的时间。我理解应用函数的想法,但非常基本,需要帮助解决这个问题。

我有这些功能(我的整个功能的一部分):

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)

有没有简单的方法来重复这些功能?

1 个答案:

答案 0 :(得分:2)

没有数据会很难,但遵循这些原则你应该能够改进你的代码:

如果你没有整齐格式的fam和par变量(如果你能控制它,你应该这样做):

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))

然后你可以在这些列表上使用apply函数:

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)
}