R - 函数简化和优化

时间:2013-11-27 22:48:08

标签: r function optimization

该函数的作用是在primes中找到list1并将它们转换为等效的a(即2将是a2,即1,1)。然后它会!NULL中的list2并搜索转换后的list1中是否存在(转换为1,2,3或4中的两个列表)。最后,它返回一个true和false的逻辑列表,稍后将使用它。即使它很难操作它看起来效率很低而且很长。寻找任何改善这一点的建议。

测试数据:

list1<-c(11,2,29,5,17)
offspring<-data.frame(matrix(unlist(list1), nrow=1, byrow=T))

list2<-c(0,11)
parent<-data.frame(matrix(unlist(list2), nrow=1, byrow=T))

先决条件:

primes <- c(2, 3, 5, 7, 11, 13, 17, 19, 23, 29)

a2 <- c(1,1)
a3 <- c(1,2)
a5 <- c(2,2)
a7 <- c(1,3)
a11 <- c(1,4)
a13 <- c(2,3)
a17 <- c(2,4)
a19 <- c(3,3)
a23 <- c(3,4)
a29 <- c(4,4)

缺少的功能:

missing <- function(offspring, parent){

  ofls <- lapply(1:ncol(offspring),FUN = function(i){get(paste0("a", offspring[i]))})
  pals <- lapply(1:length(parent[parent>0]),FUN = function(i){get(paste0("a", parent[parent>0]))})
  ofls<-data.frame(ofls)
  pals<-data.frame(pals)
  set1<- matrix(,nrow=10,ncol=1)
  set2<- matrix(,nrow=10,ncol=1)
  for(z in 1:5){
    set1[z,]<-match(ofls[1,z],pals[1,], nomatch=0)
    set1[z+5,]<-match(ofls[2,z],pals[1,], nomatch=0)
    set2[z,]<-match(ofls[1,z],pals[2,], nomatch=0)
    set2[z+5,]<-match(ofls[2,z],pals[2,], nomatch=0)

  }

  return((set1+set2)[c(1,2,3,4,5)]+(set1+set2)[c(6,7,8,9,10)]==0)


}

missing(offspring,parent)

结果:

[1]  TRUE  TRUE FALSE  TRUE FALSE

编辑: 我纠正了我发现的错误,这样做会使脚本简化很多。

编辑2: 运行该函数后,我仍然在RStudio中收到错误,然后尝试view()两个data.frames:

Error in View : argument "title" is missing, with no default

0 个答案:

没有答案