File size: 135,187 Bytes
f18999e
 
1
2
3
{"repo_name": "Get_MR", "file_name": "/Get_MR/2.0/Get_MR2.0.r", "inference_info": {"prefix_code": "library(mr.raps)\nlibrary(TwoSampleMR)\nlibrary(dplyr)\nlibrary(fs) \nlibrary(ieugwasr)\nlibrary(plinkbinr) \nlibrary(tidyr)\nlibrary(data.table)\nlibrary(MRPRESSO)\nlibrary(parallel)\nlibrary(doParallel)\nlibrary(pbapply)\nlibrary(stringr)\nlibrary(cause)\nlibrary(vroom)\nlibrary(MungeSumstats)\nlibrary(ldscr)\nlibrary(MRlap)\n\n\nselect<-dplyr::select\nmcl<-makeCluster\n\n\n## 2.0更新内容\n\nclean<-function(list,clean_0=FALSE){\n  \n  l<-pblapply(list,class)\n  ll<-c()\n  for(i in 1:length(l)){\n    if(l[[i]][1]%in% \"try-error\"){}\n    else{ll<-c(ll,i)}\n  }\n  list<-list[ll]\n  \n  if(clean_0==TRUE){\n    list<-Filter(function(x) nrow(x)!=0, list)\n  }\n  return(list)\n}\n\nget_rsid<-function(chr,pos,version='hg38'){\n  library(biomaRt)\n  dat<-data.frame(CHR=chr,start=pos,end=pos)\n  if(version==\"hg38\"){\n    ver<-listEnsemblArchives()%>%subset(name!='Ensembl GRCh37')\n    ur<-ver$url[1]\n    snp_mart <- useEnsembl(biomart=\"ENSEMBL_MART_SNP\", \n                           host=ur, \n                           dataset=\"hsapiens_snp\")\n    position <- apply(dat, 1, paste, collapse = \":\")\n    res<-getBM(attributes = c('refsnp_id', 'allele', 'chrom_start'), \n               filters = 'chromosomal_region', \n               values = position, \n               mart = snp_mart)\n  }\n  if(version==\"hg19\"){\n    snp_mart <- useEnsembl(biomart=\"ENSEMBL_MART_SNP\", \n                           host=\"https://grch37.ensembl.org\", \n                           dataset=\"hsapiens_snp\")\n    position <- apply(dat, 1, paste, collapse = \":\")\n    res<-getBM(attributes = c('refsnp_id', 'allele', 'chrom_start'), \n               filters = 'chromosomal_region', \n               values = position, \n               mart = snp_mart)\n  }\n  \n  return(res)\n}\n\nget_exposure = function(id,pval=5e-08,r2=0.001,kb=10000) {\n  library(TwoSampleMR)\n  dat<-try(data.frame(extract_instruments(id,p1=pval,clump = T,p2=1,r2=r2,kb=kb)))\n  if ('try-error'%in%class(dat))   {\n    dat=NA\n  }\n  return(dat)\n}\n\nget_outcome=function(id,expo){\n  library(TwoSampleMR)\n  dat<-try(data.frame(extract_outcome_data(expo$SNP,id,proxies = F,maf_threshold=0.4)))\n  if ('try-error'%in%class(dat))   {\n    dat=NA\n  }\n  \n  try( return(dat))\n}\n\nget_ao<-function(a=NULL){\n  ao<-available_outcomes()\n  ao<-separate(ao,id,c(\"a\",\"b\",\"c\"),sep=\"-\",remove = FALSE)\n  if(is.null(a)==F){ao<-subset(ao,a==a)}\n  return(ao)\n}\n\nget_exposure_wrong_num<-function(list){\n  res<-is.na(list)\n  num=0\n  foreach (i=1:length(res))%do%{\n    if(res[i]==TRUE) num=num+1\n  }\n  return(num)\n}\n\nclean_outcome_from_exposure<-function(expo,outcome){\n  snp<-lapply(expo,FUN=function(x)data.frame(SNP=x$SNP))\n  snp<-bind_rows(snp)\n  snp<-data.frame(SNP=unique(snp$SNP))\n  outcome_adj<-merge(outcome,snp)\n  return(outcome_adj)\n}\n\nclean_GWAS<-function(list,clean=c(\"bbj\",\"eqtl\")){\n  clean_GWAS_logit<-function(dat,clean){\n    id<-dat$id.exposure[1]\n    id<-as.data.frame(id)\n    id<-separate(id,\"id\",c('a','b','c'),sep = \"-\")\n    if(id$a==clean){\n      return(data.frame(lg=1))\n    }\n    else(return(data.frame(lg=0)))\n  }\n  print(\"正在获取指定数据集信息\")\n  for(i in 1:length(clean)){\n  lg<-pblapply(list,clean[i],FUN=clean_GWAS_logit)\n  \n  lg<-bind_rows(lg)\n  \n  list<-list[which(lg$lg==0)]\n  }\n  return(list)\n  \n}\n\n\n\ncyclemr<-function(dat,cl_num,type=\"list\"){\nclean<-function(list,clean_0=FALSE){\n  \n  l<-pblapply(list,class)\n  ll<-c()\n  for(i in 1:length(l)){\n    if(l[[i]][1]%in% \"try-error\"){}\n    else{ll<-c(ll,i)}\n  }\n  list<-list[ll]\n  \n  if(clean_0==TRUE){\n    list<-Filter(function(x) nrow(x)!=0, list)\n  }\n  return(list)\n}\n  # base mr\n  mr_base<-function(dat){\n    library(TwoSampleMR)\n    library(dplyr)\n    try(mr<-mr(dat) )\n    try(mr<-dplyr::select(mr,id.exposure,id.outcome,method,nsnp,b,se,pval)) \n    try(mr_OR<-generate_odds_ratios(mr_res = mr(dat)))\n    try(mr_OR<-dplyr::select(mr_OR,id.exposure,id.outcome,method,nsnp,b,se,pval,lo_ci,up_ci,or, or_lci95,or_uci95))\n    try(mr_OR<-dplyr::rename(mr_OR,b.OR=\"b\",se.OR=\"se\",pval.OR=\"pval\"))\n    try( mr_p_OR<-merge(mr,mr_OR))\n    try(return(mr_p_OR))\n  }\n  \n  mr_egger<-function(dat){\n    library(TwoSampleMR)\n    library(dplyr)\n    mr_egger<-mr_pleiotropy_test(dat) \n    try( mr_egger<-dplyr::select(mr_egger,id.exposure,id.outcome,egger_intercept,se,pval))\n    try( mr_egger<-dplyr::rename(mr_egger,se.egger=\"se\",pval.egger=\"pval\"))\n    try( mr_egger[2:5,]<-NA) \n    try( return(mr_egger))\n  }\n  \n  mr_test<-function(dat){\n    library(TwoSampleMR)\n    library(dplyr)\n    mr_heterogeneity<-mr_heterogeneity(dat)\n    try (mr_heterogeneity<-dplyr::select(mr_heterogeneity,id.exposure,id.outcome,method,Q, Q_df,Q_pval))\n    try( mr_heterogeneity<-dplyr::rename(mr_heterogeneity,method.he=\"method\"))\n    try (mr_heterogeneity[3:5,]<-NA )\n    try( return(mr_heterogeneity))\n  }\n  \n  # presso\n  cycle_presso<-function(dat){\n    library(TwoSampleMR)\n    library(MRPRESSO)\n    library(dplyr) \n    nsnp_filter=6\n    try (mr_presso_res<-mr_presso(BetaOutcome =\"beta.outcome\", BetaExposure = \"beta.exposure\", SdOutcome =\"se.outcome\", SdExposure = \"se.exposure\", \n                                  OUTLIERtest = TRUE,DISTORTIONtest = TRUE, data = dat,  \n                                  SignifThreshold = 0.05))\n    try ( mr_presso_main<-mr_presso_res$`Main MR results`)\n    try(mr_presso_main)\n    try ( mr_presso_main[3:5,]<-NA)\n    try(  return(mr_presso_main))\n  }\n  \n  mr_Presso<-function(dat,num=10000){\n    library(TwoSampleMR)\n    library(MRPRESSO)\n    library(dplyr)\n    \n    nsnp_filter=6\n    set.seed(123)\n    try (mr_presso_res<-mr_presso(BetaOutcome =\"beta.outcome\", BetaExposure = \"beta.exposure\", SdOutcome =\"se.outcome\", SdExposure = \"se.exposure\", \n                                  OUTLIERtest = TRUE,DISTORTIONtest = TRUE, data = dat,  \n                                  SignifThreshold = 0.05,NbDistribution = num))\n    return(mr_presso_res)\n    \n  }\n  mr_presso_pval<-function(mr_presso_res){ \n    try ( mr_presso_main<-mr_presso_res$`Main MR results`)\n    try ( mr_presso_main[3:5,]<-NA) \n    return(mr_presso_main)\n  }\n  \n  \n  mr_presso_snp<-function(mr_presso_res,mr_presso_main,dat,type=\"list\"){\n    data_re<-list()\n    if(type==\"list\"){\n      for(i in 1:length(mr_presso_res)){\n        res<-mr_presso_res$`MR-PRESSO results`[[i]]\n        main<-mr_presso_main[[i]]\n        data<-dat[[i]]\n        try(if(is.na(main[2,6])==FALSE){\n          outliers<-which(res$`Outlier Test`$Pvalue<0.05)\n          data$mr_keep[outliers]<-FALSE\n        })\n        data_re[[i]]<-data\n        names(data_re)[[i]]<-names(dat)[[i]]\n      }\n      return(data_re)\n    }\n    \n    if(type==\"data\"){\n      res<-mr_presso_res$`MR-PRESSO results`\n      main<-mr_presso_main\n      data<-dat\n      try(if(is.na(main[2,6])==FALSE){\n        outliers<-which(res$`Outlier Test`$Pvalue<0.05)\n        data$mr_keep[outliers]<-FALSE\n      })\n      return(data)\n    }\n  }\n  bind_basemr<-function(base.res,egger.res,test.res){\n    res_all<-data.frame()\n    for(i in 1:nrow(base.res)){\n      if(i%%5==1){\n        id<-base.res$id.exposure[i]\n        num.bg<-which(egger.res$id.exposure==id)\n        num.end<-num.bg+4\n        res<-cbind(base.res[i:(i+4),],egger.res[num.bg:num.end,3:5])\n        num.bg<-which(test.res$id.exposure==id)[1]\n        num.end<-num.bg+4\n        res<-cbind(res,test.res[num.bg:num.end,3:6])\n        res_all<-rbind(res_all,res)\n      }\n    }\n    return(res_all)\n  }\n  \n  if(type==\"list\"){\n    cl <- makeCluster(cl_num) \n    \n    base.res<-pblapply(dat, FUN=mr_base,cl=cl)\n    \n    egger.res<-pblapply(dat, FUN=mr_egger)\n    \n    test.res<-pblapply(dat,FUN=mr_test)\n    \n    stopCluster(cl)\n    \n    base.res<-clean(base.res)\n    \n    egger.res<-clean(egger.res)\n    \n    test.res<-clean(test.res)\n    \n    base.res<-bind_rows (base.res)\n    \n    base.res<-subset(base.res,nsnp>2) ## 防止出现wald ratio,导致错误\n    \n    egger.res<-bind_rows (egger.res)\n    \n    test.res<-bind_rows (test.res)\n    \n    res_all<-bind_basemr(base.res,egger.res,test.res)\n    \n  }\n  \n  if(type==\"data\"){\n    \n    presso_res<-mr_Presso(dat,10000)\n    \n    presso_pval<-mr_presso_pval(presso_res)\n    \n    dat_aj<-mr_presso_snp(presso_res,presso_pval,dat,\"data\")\n    \n    base.res<-mr_base(dat)\n    \n    egger.res<-mr_egger(dat)\n    \n    test.res<-mr_test(dat)\n    \n    base.res<-bind_rows (base.res)\n    \n    res_all<-cbind(base.res,presso_pval,egger.res,test.res)\n  }\n  \n  return(res_all)\n}\n\n\nbind_basemr<-function(base.res,egger.res,test.res){\n  res_all<-data.frame()\n  for(i in 1:nrow(base.res)){\n    if(i%%5==1){\n      id<-base.res$id.exposure[i]\n      num.bg<-which(egger.res$id.exposure==id)\n      num.end<-num.bg+4\n      res<-cbind(base.res[i:(i+4),],egger.res[num.bg:num.end,3:5])\n      num.bg<-which(test.res$id.exposure==id)[1]\n      num.end<-num.bg+4\n      res<-cbind(res,test.res[num.bg:num.end,3:6])\n      res_all<-rbind(res_all,res)\n    }\n  }\n  return(res_all)\n}\n\n\nbind_pressomr<-function(base_res,presso_pval,egger_res,test_res){\n  \n  presso_id<-names(presso_pval)\n  presso_pval<-bind_rows(presso_pval)\n  base_res<-bind_rows(base_res)\n  egger_res<-bind_rows(egger_res)\n  test_res<-bind_rows(test_res)\n  \n  res_all<-data.frame()\n  for(i in 1:nrow(base_res)){\n    if(i%%5==1){\n      id<-base_res$id.exposure[i]\n      \n      num.bg<-5*(which(presso_id==id)[1]-1)+1\n      num.end<-num.bg+4\n      res<-cbind(base_res[i:(i+4),],presso_pval[num.bg:num.end,2:6])\n      \n      num.bg<-which(egger_res$id.exposure==id)\n      num.end<-num.bg+4\n      res<-cbind(res,egger_res[num.bg:num.end,3:5])\n      \n      num.bg<-which(test_res$id.exposure==id)[1]\n      num.end<-num.bg+4\n      res<-cbind(res,test_res[num.bg:num.end,3:6])\n      \n      res_all<-rbind(res_all,res)\n    }\n  }\n  return(res_all)\n}\n\n\nbind_trait<-function(res_all,ao){\n  res_all<-data.frame(trait=NA,res_all)\n  for(i in 1:nrow(res_all)){\n    try( num<-which(ao$id==res_all$id.exposure[i]))\n    try( res_all$trait[i]<-ao$trait[num])\n  }\n  return(res_all)\n}\n\nbind_trait_outcome<-function(res_all,ao){\n  res_all<-data.frame(trait=NA,res_all)\n  for(i in 1:nrow(res_all)){\n    num<-which(ao$id==res_all$id.outcome[i])\n    res_all$trait[i]<-ao$trait[num]\n  }\n  return(res_all)\n}\n\nclean_cl<-function(){\n  cl<<-makeCluster(1)\n  stopCluster(cl)\n  gc()\n}\n\nclean_GWAS_id<-", "suffix_code": "\n\n\n## 1.0内容\n# format\nformat_Mun<-function(file,source=\"finn_r8\",save_path=NULL,lift=F,ref_genome = \"hg38\",\n                     convert_ref_genome = \"hg19\"){\n  library(data.table)\n  library(MungeSumstats)\n  library(dplyr)\n  if(class(file)!=\"data.frame\"){\n    dat<-fread(file)\n    if(source==\"finn_r8\"){\n      dat<-dat%>%dplyr::select(SNP=rsids,CHR=`#chrom`,BP=pos,A1=ref,\n                               A2=alt,FRQ=af_alt,BETA=beta,\n                               SE=sebeta,P=pval)\n    }\n  }\n  dat<-as.data.frame(dat)\n  dat<-format_sumstats(dat,return_data = TRUE)\n  if(is.null(save_path)==F){setwd(save_path)}\n  dat<-fwrite(dat,paste0(file,'(Mun_format',ref_genome,').gz'))\n  te<-fs::dir_info( tempdir())\n  te<-subset(te,size>1e+8)\n  fs::file_delete(te$path)\n  if(lift==T){\n    dat <- MungeSumstats::liftover(sumstats_dt = dat, \n                                   ref_genome = ref_genome,\n                                   convert_ref_genome = convert_ref_genome)\n    dat<-fwrite(dat,paste0(file,'(Mun_format',convert_ref_genome,').gz'))\n  }\n  gc()\n}\n\nformat_cyclemr<-function(data,type=\"exposure\",source=\"finn_r8\"){\n  library(TwoSampleMR)\n  library(MungeSumstats)\n  \n  if(source==\"finn_r8\"){\n    data<-format_data(data,type=type,\n                      id_col = \"id\",chr_col =\"#chrom\",pos=\"pos\",\n                      snp_col = \"rsids\",beta_col = \"beta\",se_col = \"sebeta\",\n                      effect_allele_col = \"alt\",other_allele_col = \"ref\",\n                      eaf_col = \"af_alt\",phenotype_col = \"phenotype\",pval_col = \"pval\")\n  }\n  \n  \n  \n  if(source==\"ukb_nosnp\"){\n    data<-separate(data,variant,c(\"chr\",\"pos\",\"ref\",\"alt\"),sep = \":\")\n    \n    data<-dplyr::select(data,chr,pos,ref,alt,minor_AF,beta,se,pval)\n    name<-colnames(data)\n    colnames(data) <-c('CHR','BP','A1','A2','FRQ','BETA', 'SE','P')\n    \n    expo_rs_done<-format_sumstats(data,ref_genome = \"GRCh37\",return_data = TRUE)\n    \n    expo_rs_done$BP<-as.character(expo_rs_done$BP)\n    colnames(data)<-name\n    data<-merge(data,expo_rs_done,by.x=c(\"chr\",\"pos\"),by.y=c(\"CHR\",\"BP\"),all.x=TRUE)\n    \n    data<-format_data(data,type=type,\n                      samplesize_col = \"n_complete_samples\",\n                      snp_col = \"SNP\",effect_allele_col = \"alt\",\n                      other_allele_col = \"ref\",eaf_col =\"minor_AF\",\n                      beta_col=\"beta\",se_col = \"se\",pval_col = \"pval\",\n                      chr_col=\"chr\",pos_col =\"pos\",id='id',phenotype_col = 'phenotype')\n  }\n  \n  if(source==\"Mun\"){\n    data<-format_data(data,type=type,\n                      snp_col = 'SNP',\n                      chr_col = 'CHR',\n                      pos_col = 'BP',\n                      effect_allele_col = 'A2',\n                      other_allele_col = \"A1\",\n                      se_col = 'SE',\n                      beta_col= 'BETA',\n                      eaf_col = 'FRQ',\n                      id_col = 'id',\n                      phenotype_col = \"phenotype\",\n                      pval_col = \"P\"\n    )\n  }\n  \n  if(source==\"covid\"){\n    data<-format_data(data,type=type,\n                      id_col = \"id\",chr_col =\"#CHR\",pos=\"POS\",\n                      snp_col = \"rsid\",beta_col = \"all_inv_var_meta_beta\",se_col = \"all_inv_var_meta_sebeta\",\n                      effect_allele_col = \"ALT\",other_allele_col = \"REF\",\n                      eaf_col = \"all_meta_AF\",phenotype_col = \"phenotype\",\n                      ncase_col = \"all_inv_var_meta_cases\",ncontrol_col = \"all_inv_var_meta_controls\",\n                      pval_col = \"all_inv_var_meta_p\")\n  }\n  \n  if(source==\"outcome\"){\n    data<-format_data(data,type=type,\n                      id_col = \"id.outcome\",chr_col =\"chr.outcome\",pos=\"pos.outcome\",\n                      snp_col = \"SNP\",beta_col = \"beta.outcome\",se_col = \"se.outcome\",\n                      effect_allele_col = \"effect_allele.outcome\",other_allele_col = \"other_allele.outcome\",\n                      eaf_col = \"eaf.outcome\",phenotype_col = \"outcome\",\n                      samplesize_col = \"samplesize.outcome\",\n                      pval_col = \"pval.outcome\")\n    \n  }\n  if(source==\"exposure\"){\n    data<-format_data(data,type=type,\n                      id_col = \"id.exposure\",chr_col =\"chr.exposure\",pos=\"pos.exposure\",\n                      snp_col = \"SNP\",beta_col = \"beta.exposure\",se_col = \"se.exposure\",\n                      effect_allele_col = \"effect_allele.exposure\",other_allele_col = \"other_allele.exposure\",\n                      eaf_col = \"eaf.exposure\",phenotype_col = \"exposure\",\n                      samplesize_col = \"samplesize.exposure\",\n                      pval_col = \"pval.exposure\")\n    \n  }\n  \n  if(source==\"fast_ukb\"){\n    data<-format_data(data,type=type,id_col=\"id\",\n                      phenotype_col = \"phenotype\",snp_col = \"SNP\",\n                      effect_allele_col = \"A1\",other_allele_col = \"A2\",\n                      eaf_col =\"AF1\",beta_col=\"BETA\",se_col = \"SE\",\n                      pval_col = \"P\",chr_col = \"CHR\",pos_col = \"POS\")\n  }\n  \n  \n  \n  if(source==\"bac\"){\n    data<-format_data(data,type=type,id_col=\"bac\",\n                      phenotype_col = \"phenotype\",snp_col = \"rsID\",\n                      effect_allele_col = \"eff.allele\",other_allele_col = \"ref.allele\",\n                      beta_col=\"beta\",se_col = \"SE\",\n                      pval_col = \"P.weightedSumZ\",chr_col = \"chr\",pos_col = \"bp\",samplesize_col = \"N\")\n  }\n  \n  if(source==\"finn_r7\"){\n    data<-format_data(data,type=type,snp_col = \"rsids\",\n                      effect_allele_col = \"alt\",other_allele_col = \"ref\",\n                      beta_col=\"beta\",se_col = \"sebeta\",eaf_col = \"af_alt\",\n                      pval_col = \"pval\",chr_col = \"chrom\",pos_col = \"pos\")\n  }\n  return(data)\n}\n\n\nformat_trait<-function(list,short=FALSE,short_num=\"40\"){\n  for(i in 1:length(list)){\n    expo<-data.frame(exposure=list[[i]]\n                     $exposure)\n    try(expo<-separate(expo,exposure,c('a','b'),sep='\\\\|\\\\|'))\n    if(short==TRUE){try(expo$a <- substr(expo$a, 1, short_num))}\n    try(expo<-expo$a)\n    try(expo<-gsub(\":\",\"_\",expo))\n    try(expo<-gsub(\"-\",\"_\",expo))\n    try(expo<-gsub(\" \",\"_\",expo))\n    try(expo<-gsub(\",\",\"_\",expo))\n    try(expo<-gsub(\"/\",\"_\",expo))\n    list[[i]]$exposure<-expo[1]\n    \n  }\n  \n  \n  return(list)\n}\n\n# read\nread_vcf_getmr<-function(file_name,nThread = 8,type=\".gz\"){\n  name<-file_name\n  \n  for(i in 1:nrow(name)){\n    dat<-read_sumstats(paste0(\"./\",name[i]),nThread = nThread,nrow=Inf,standardise_headers = FALSE,mapping_file = sumstatsColHeaders)\n    \n    vroom_write(dat,paste0(name[i],type))\n    \n    gc()\n  }\n  print(i)\n  \n}\n\nread_easy<-function(file_name,pval=5e-08){\n  library(data.table)\n  dat<-fread(file_name)\n  dat<-subset(dat,pval.exposure<pval)\n  return(dat)\n}\n\n\n# get\nget_eaf_from_1000G<-function(dat,path,type=\"exposure\"){\n  \n  corrected_eaf_expo<-function(data_MAF){\n    effect=data_MAF$effect_allele.exposure\n    other=data_MAF$other_allele.exposure\n    A1=data_MAF$A1\n    A2=data_MAF$A2\n    MAF_num=data_MAF$MAF\n    EAF_num=1-MAF_num\n    \n    harna<-is.na(data_MAF$A1)\n    harna<-data_MAF$SNP[which(harna==T)]\n    \n    cor1<-which(data_MAF$effect_allele.exposure !=data_MAF$A1)\n    \n    \n    data_MAF$eaf.exposure=data_MAF$MAF\n    data_MAF$type=\"raw\"\n    data_MAF$eaf.exposure[cor1]=EAF_num[cor1]\n    data_MAF$type[cor1]=\"corrected\"\n    cor2<-which(data_MAF$other_allele.exposure ==data_MAF$A1)\n    cor21<-setdiff(cor2,cor1)\n    cor12<-setdiff(cor1,cor2)\n    error<-c(cor12,cor21)\n    data_MAF$eaf.exposure[error]=NA\n    data_MAF$type[error]=\"error\"\n    \n    data_MAF<-list(data_MAF=data_MAF,cor1=cor1,harna=harna,error=error)\n    \n    return(data_MAF)\n    \n  }\n  \n  corrected_eaf_out<-function(data_MAF){\n    effect=data_MAF$effect_allele.outcome\n    other=data_MAF$other_allele.outcome\n    A1=data_MAF$A1\n    A2=data_MAF$A2\n    MAF_num=data_MAF$MAF\n    EAF_num=1-MAF_num\n    \n    harna<-is.na(data_MAF$A1)\n    harna<-data_MAF$SNP[which(harna==T)]\n    \n    cor1<-which(data_MAF$effect_allele.outcome !=data_MAF$A1)\n    \n    \n    data_MAF$eaf.outcome=data_MAF$MAF\n    data_MAF$type=\"raw\"\n    data_MAF$eaf.outcome[cor1]=EAF_num[cor1]\n    data_MAF$type[cor1]=\"corrected\"\n    cor2<-which(data_MAF$other_allele.outcome ==data_MAF$A1)\n    cor21<-setdiff(cor2,cor1)\n    cor12<-setdiff(cor1,cor2)\n    error<-c(cor12,cor21)\n    data_MAF$eaf.outcome[error]=NA\n    data_MAF$type[error]=\"error\"\n    \n    data_MAF<-list(data_MAF=data_MAF,cor1=cor1,harna=harna,error=error)\n    \n    return(data_MAF)\n    \n  }\n  \n  if(type==\"exposure\" && (is.na(dat$eaf.exposure[1])==T || is.null(dat$eaf.exposure)==T)){\n    r<-nrow(dat)\n    \n    setwd(path)\n    MAF<-fread(\"fileFrequency.frq\",header = T)\n    \n    dat<-merge(dat,MAF,by.x = \"SNP\",by.y = \"SNP\",all.x = T)\n    \n    dat<-corrected_eaf_expo(dat)\n    \n    cor1<-dat$cor1\n    \n    harna<-dat$harna\n    \n    error<-dat$error\n    \n    dat<-dat$data_MAF\n    \n    print(paste0(\"一共有\",(r-length(harna)-length(error)),\"个SNP成功匹配EAF,占比\",(r-length(harna)-length(error))/r*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(cor1),\"个SNP是major allele,EAF被计算为1-MAF,在成功匹配数目中占比\",length(cor1)/(r-length(harna)-length(error))*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(harna),\"个SNP在1000G中找不到,占比\",length(harna)/r*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(error),\"个SNP在输入数据与1000G中效应列与参照列,将剔除eaf,占比\",length(error)/r*100,\"%\"))\n    \n    print(\"输出数据中的type列说明:\")\n    print(\"raw:EAF直接等于1000G里的MAF数值,因为效应列是minor allele\")\n    print('corrected:EAF等于1000G中1-MAF,因为效应列是major allele')\n    print(\"error:输入数据与1000G里面提供的数据完全不一致,比如这个SNP输入的效应列是C,参照列是G,但是1000G提供的是A-T,这种情况下,EAF会被清空(NA),当成匹配失败\")\n    \n    return(dat)\n  }\n  \n  if(type==\"outcome\" && (is.na(dat$eaf.outcome[1])==T || is.null(dat$eaf.outcome)==T)){\n    r<-nrow(dat)\n    \n    setwd(path)\n    MAF<-fread(\"fileFrequency.frq\",header = T)\n    \n    dat<-merge(dat,MAF,by.x = \"SNP\",by.y = \"SNP\",all.x = T)\n    \n    dat<-corrected_eaf_out(dat)\n    \n    cor1<-dat$cor1\n    \n    harna<-dat$harna\n    \n    error<-dat$error\n    \n    dat<-dat$data_MAF\n    \n    print(paste0(\"一共有\",(r-length(harna)-length(error)),\"个SNP成功匹配EAF,占比\",(r-length(harna)-length(error))/r*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(cor1),\"个SNP是major allele,EAF被计算为1-MAF,在成功匹配数目中占比\",length(cor1)/(r-length(harna)-length(error))*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(harna),\"个SNP在1000G找不到,占比\",length(harna)/r*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(error),\"个SNP在输入数据与1000G中效应列与参照列,将剔除eaf,占比\",length(error)/r*100,\"%\"))\n    \n    print(\"输出数据中的type列说明:\")\n    print(\"raw:EAF直接等于1000G里的MAF数值,因为效应列是minor allele\")\n    print('corrected:EAF等于1000G中1-MAF,因为效应列是major allele')\n    print(\"error:输入数据与1000G里面提供的数据完全不一致,比如这个SNP输入的效应列是C,参照列是G,但是1000G提供的是A-T,这种情况下,EAF会被清空(NA),当成匹配失败\")\n    \n    return(dat)\n  }\n  else{return(dat)}\n}\n\nget_chr_pos<-function(dat,type=\"exposure\"){\n  if(type==\"exposure\"){\n    if(is.na(dat$eaf.exposure[1])==T || is.null(dat$eaf.exposure)==T){\n      print(\"需要先运行get_eaf_from_1000G来匹配eaf,再匹配chr和pos\")\n    }\n    else{\n      dat_d<-dat%>%select(SNP,effect_allele.exposure,other_allele.exposure,eaf.exposure,beta.exposure,se.exposure,pval.exposure)\n      colnames(dat_d) <-c('SNP','A1','A2','FRQ','BETA', 'SE','P')\n      dat_d<-format_sumstats(dat_d,ref_genome = \"GRCh37\",return_data = TRUE)\n      dat_d<-format_data(dat_d,type=type,\n                         snp_col = 'SNP',\n                         chr_col = 'CHR',\n                         pos_col = 'BP',\n                         effect_allele_col = 'A1',\n                         other_allele_col = \"A2\",\n                         se_col = 'SE',\n                         beta_col= 'BETA',\n                         eaf_col = 'FRQ',\n                         pval_col = \"P\"\n      )\n      dat_d<-dat_d%>%select(SNP,chr.exposure,pos.exposure)\n      dat<-merge(dat,dat_d,by=\"SNP\",all.x=T)\n      \n      return(dat)\n    }\n  }\n  if(type==\"outcome\"){\n    if(is.na(dat$eaf.outcome[1])==T || is.null(dat$eaf.outcome)==T){\n      print(\"需要先运行get_eaf_from_1000G来匹配eaf,再匹配chr和pos\")\n    }\n    else{\n      dat_d<-dat%>%select(SNP,effect_allele.outcome,other_allele.outcome,eaf.outcome,beta.outcome,se.outcome,pval.outcome)\n      colnames(dat_d) <-c('SNP','A1','A2','FRQ','BETA', 'SE','P')\n      dat_d<-format_sumstats(dat_d,ref_genome = \"GRCh37\",return_data = TRUE)\n      dat_d<-format_data(dat_d,type=type,\n                         snp_col = 'SNP',\n                         chr_col = 'CHR',\n                         pos_col = 'BP',\n                         effect_allele_col = 'A1',\n                         other_allele_col = \"A2\",\n                         se_col = 'SE',\n                         beta_col= 'BETA',\n                         eaf_col = 'FRQ',\n                         pval_col = \"P\"\n      )\n      dat_d<-dat_d%>%select(SNP,chr.outcome,pos.outcome)\n      dat<-merge(dat,dat_d,by=\"SNP\",all.x=T)\n      \n      return(dat)\n    }\n    \n  }\n}\n\nget_f<-function(dat,F_value=10){\n  log<-is.na(dat$eaf.exposure)\n  log<-unique(log)\n  if(length(log)==1)\n  {if(log==TRUE){\n    print(\"数据不包含eaf,无法计算F统计量\")\n    return(dat)}\n  }\n  if(is.null(dat$beta.exposure[1])==T || is.na(dat$beta.exposure[1])==T){print(\"数据不包含beta,无法计算F统计量\")\n    return(dat)}\n  if(is.null(dat$se.exposure[1])==T || is.na(dat$se.exposure[1])==T){print(\"数据不包含se,无法计算F统计量\")\n    return(dat)}\n  if(is.null(dat$samplesize.exposure[1])==T || is.na(dat$samplesize.exposure[1])==T){print(\"数据不包含samplesize(样本量),无法计算F统计量\")\n    return(dat)}\n  \n  \n  if(\"FALSE\"%in%log && is.null(dat$beta.exposure[1])==F && is.na(dat$beta.exposure[1])==F && is.null(dat$se.exposure[1])==F && is.na(dat$se.exposure[1])==F && is.null(dat$samplesize.exposure[1])==F && is.na(dat$samplesize.exposure[1])==F){\n    R2<-(2*(1-dat$eaf.exposure)*dat$eaf.exposure*(dat$beta.exposure^2))/((2*(1-dat$eaf.exposure)*dat$eaf.exposure*(dat$beta.exposure^2))+(2*(1-dat$eaf.exposure)*dat$eaf.exposure*(dat$se.exposure^2)*dat$samplesize.exposure))\n    F<- (dat$samplesize.exposure-2)*R2/(1-R2)\n    dat$R2<-R2\n    dat$F<-F\n    dat<-subset(dat,F>F_value)\n    return(dat)\n  }\n}\n\n\n# MR\ncause_getmr<-function(expo,outcome,LD_file,r2=0.001,\n                      kb=10000,pval=1e-05,cl=NULL){\n  format_cause_expo<-function(dat){\n    library(cause)\n    dat<-gwas_format(dat,snp='SNP',beta_hat ='beta.exposure',\n                     se='se.exposure',A1=\"effect_allele.exposure\",\n                     A2=\"other_allele.exposure\",chrom='chr.exposure',\n                     pos=\"pos.exposure\",p_value = 'pval.exposure'\n    )\n    return(dat)\n  }\n  format_cause_out<-function(dat){\n    library(cause)\n    dat<-gwas_format(dat,snp='SNP',beta_hat ='beta.outcome',\n                     se='se.outcome',A1=\"effect_allele.outcome\",\n                     A2=\"other_allele.outcome\",chrom='chr.outcome',\n                     pos=\"pos.outcome\",p_value = 'pval.outcome'\n    )\n    return(dat)\n  }\n  sample_cause<-function(dat,num_snp){\n    set.seed(123)\n    VAR<-with(dat,sample(snp,size=num_snp,replace=FALSE))\n    return(VAR)\n  }\n  datap_cause<-function(dat){\n    dat$p1<-pnorm(abs(dat$beta_hat_1/dat$seb1),lower.tail=F)*2\n    return(dat)\n  }\n  dat_clump_cause<-function(dat){\n    for_clump<-data.frame(dat$snp,dat$p1)\n    colnames(for_clump)<-c('rsid','pval')\n    return(for_clump)\n  }\n  datap_cause<-function(dat){\n    dat$p1<-pnorm(abs(dat$beta_hat_1/dat$seb1),lower.tail=F)*2\n    return(dat)\n  }\n  ld_local<-function(dat,r2,kb,p,LD_file){\n    library(plinkbinr)\n    \n    plink_pathway<-get_plink_exe()\n    \n    dat<-ld_clump(dat,clump_r2 = r2,clump_kb = kb,\n                  clump_p = p,\n                  plink_bin =plink_pathway , bfile =LD_file)\n    \n    return(dat)\n  }\n  if(\"list\"%in%class(outcome)){\n    single_expo=T\n    single_outcome=F}\n  if(\"list\"%in%class(expo)){\n    single_outcome=T\n    single_expo=F}\n  if(single_expo==T){\n    outcome<-pblapply(outcome,FUN=format_cause_out,cl=cl)\n    expo<-format_cause_expo(expo)\n  }\n  if(single_outcome==T){\n    expo<-pblapply(expo,FUN=format_cause_expo,cl=cl)\n    outcome<-format_cause_out(outcome)\n  }\n  \n  \n  if(single_outcome==T){dat<-pblapply(expo,outcome,FUN=gwas_merge,cl=cl)}\n  if(single_expo==T){dat<-pblapply(outcome,expo,\n                                   FUN=function(outcome,exposure)gwas_merge(exposure,outcome),\n                                   cl=cl)}\n  \n  \n  VAR<-pblapply(dat,1000000,FUN=sample_cause)\n  \n  est<-foreach(i=1:length(VAR)) %do%{\n    library(cause)\n    data<-est_cause_params(dat[[i]],VAR[[i]])\n  }\n  dat<-pblapply(dat,FUN=datap_cause)\n  for_clump<-lapply(dat, dat_clump_cause)\n  clumped<-pblapply(for_clump,0.001,10000,1e-05,LD_file,FUN=ld_local)\n  top_vars<-pblapply(clumped,FUN=function(dat) return(dat$rsid))\n  cause_res<-list()\n  for(i in 1:length(dat)){\n    library(cause)\n    res<-cause(dat[[i]],est[[i]],top_vars[[i]])\n    cause_res[[i]]<-res\n    print(i)\n  }\n  cause_table<-data.frame()\n  for (i in 1:length(cause_res)){\n    res<-cause_res[[i]]\n    elpd<-res$elpd\n    elpd$p<-pnorm(-elpd$z,lower.tail = F)\n    name<-paste0('file',i)\n    elpd$file<-name\n    cause_table<-rbind(cause_table,elpd)\n  }\n  return(cause_table)\n}\n\n# RAPS\nRAPS_getmr<-function(dat,dir_figure){\n  setwd(dir_figure)\n  res<-try(mr.raps(dat,over.dispersion = TRUE))\n  if(class(res)%in%\"try-error\"){}\n  else{\n    exposure<-dat$id.exposure\n    dir_create(exposure)\n    dir_in<-paste0(dir_figure,'/',exposure)\n    setwd(dir_in)\n    #plot_name<-paste0(exposure,'raps.pdf')\n    ggsave(file='raps_plot.pdf',plot=plot(res),width=9,height=5)\n    res<-data.frame(beta.raps=res$beta.hat,se.raps=res$beta.se,\n                    eov=res$tau2.hat,se.eov=res$tau2.se,OR.raps=NA,\n                    or_lci95.raps=NA,or_uci95.raps=NA)\n    res$OR.raps<- exp(res$beta.raps)\n    res$or_lci95.raps<-exp(res$beta.raps)-(res$beta.raps*1.96)\n    res$or_uci95.raps<-exp(res$beta.raps)+(res$beta.raps*1.96)\n    res$pval.raps<-2*pnorm(abs(res$beta.raps/res$se.raps),lower.tail=F) \n    res$pval.eov<-2*pnorm(abs(res$eov/res$se.eov),lower.tail=F)\n    if(is.na(res$pval.eov)==FALSE){\n      if(res$pval.eov >0.05 ){\n        res1<-mr.raps(dat,over.dispersion = F)\n        setwd(dir_in)\n        #plot_name<-paste0(exposure,'raps.pdf')\n        ggsave(file='raps_plot.pdf',plot=plot(res1),width=9,height=5)\n        res1<-data.frame(beta.raps=res1$beta.hat,se.raps=res1$beta.se,\n                         eov=NA,se.eov=NA)\n        res1$eov<-res$eov\n        res1$se.eov<-res$se.eov\n        res1$OR.raps<- exp(res1$beta.raps)\n        res1$or_lci95.raps<-exp(res1$beta.raps)-(res1$beta.raps*1.96)\n        res1$or_uci95.raps<-exp(res1$beta.raps)+(res1$beta.raps*1.96)\n        res1$pval.raps<-2*pnorm(abs(res1$beta.raps/res1$se.raps),lower.tail=F) \n        res1$pval.eov<-2*pnorm(abs(res1$eov/res1$se.eov),lower.tail=F)\n        \n        res<-res1\n      }\n    }\n    \n    return(res)\n  }\n}\n\nmr_dircreate_base<-function(root_dir,project_name,date=NULL){  \n  library(fs)\n  dir_name<-root_dir\n  setwd(dir_name)\n  \n  if(is.null(date)==FALSE){data_u<-date}else{data_u<-Sys.Date()}\n  \n  dir_name2<-project_name\n  dir_name3<-paste0(dir_name2,data_u)\n  dir_create(dir_name3)\n  setwd(paste0(dir_name,\"/\",dir_name3))\n  dir_name4<-\"1.figure\"\n  dir_name5<-\"2.table\"\n  dir_name6<-\"3.figure of sig res\"\n  dir_name7<-\"4.snp with Fval\"\n  \n  paste<-paste0(dir_name,\"/\",dir_name3,\"/\")\n  \n  dir1<-paste0(paste,dir_name4)\n  dir.create(dir1)\n  \n  dir2<-paste0(paste,dir_name5)\n  dir.create(dir2)\n  \n  dir3<-paste0(paste,dir_name6)\n  dir.create(dir3)\n  \n  dir4<-paste0(paste,dir_name7)\n  dir.create(dir4)\n  \n  res<-list(paste=paste,dir1=dir1,dir2=dir2,dir3=dir3,dir4=dir4)\n  \n  return(res)\n}\n\n\n\n# PRESSO\nmr_Presso<-function(dat,num=10000){\n  library(TwoSampleMR)\n  library(MRPRESSO)\n  library(dplyr)\n  \n  nsnp_filter=6\n  set.seed(123)\n  try (mr_presso_res<-mr_presso(BetaOutcome =\"beta.outcome\", BetaExposure = \"beta.exposure\", SdOutcome =\"se.outcome\", SdExposure = \"se.exposure\", \n                                OUTLIERtest = TRUE,DISTORTIONtest = TRUE, data = dat,  \n                                SignifThreshold = 0.05,NbDistribution = num))\n  return(mr_presso_res)\n  \n}\nmr_presso_pval<-function(mr_presso_res){ \n  try ( mr_presso_main<-mr_presso_res$`Main MR results`)\n  try ( mr_presso_main[3:5,]<-NA) \n  return(mr_presso_main)\n}\n\n\nmr_presso_snp<-function(mr_presso_res,mr_presso_main,dat,type=\"list\"){\n  data_re<-list()\n  if(type==\"list\"){\n    for(i in 1:length(mr_presso_res)){\n      res<-mr_presso_res[[i]]\n      main<-mr_presso_main[[i]]\n      data<-dat[[i]]\n      try(if(is.na(main[2,6])==FALSE){\n        outliers<-which(res$`MR-PRESSO results`$`Outlier Test`$Pvalue<0.05)\n        data$mr_keep[outliers]<-FALSE\n      })\n      data_re[[i]]<-data\n      names(data_re)[[i]]<-names(dat)[[i]]\n    }\n    return(data_re)\n  }\n  \n  if(type==\"data\"){\n    res<-mr_presso_res$`MR-PRESSO results`\n    main<-mr_presso_main\n    data<-dat\n    try(if(is.na(main[2,6])==FALSE){\n      outliers<-which(res$`MR-PRESSO results`$`Outlier Test`$Pvalue<0.05)\n      data$mr_keep[outliers]<-FALSE\n    })\n    return(data)\n  }\n}\n\n#MRlap\n\nmr_lap<-function(expo,outcome,ld,hm3,pval,r2,kb,MR_reverse=1e-03,save_logfiles=F){\n  expo<-expo%>%select(rsid=SNP,chr=chr.exposure,pos=pos.exposure,alt=effect_allele.exposure,\n                      ref=other_allele.exposure,N=samplesize.exposure,beta=beta.exposure,\n                      se=se.exposure)\n  expo<-as.data.frame(expo)\n  outcome<-outcome%>%select(rsid=SNP,chr=chr.outcome,pos=pos.outcome,alt=effect_allele.outcome,\n                            ref=other_allele.outcome,N=samplesize.outcome,beta=beta.outcome,\n                            se=se.outcome)\n  outcome<-as.data.frame(outcome)\n  n_expo<-expo$exposure[1]\n  n_out<-outcome$outcome[1]\n  \n  try(res<-MRlap::MRlap(exposure = expo,\n                        exposure_name = n_expo,\n                        outcome = outcome,\n                        outcome_name = n_out,\n                        ld = ld,\n                        hm3 = hm3,MR_threshold=pval,MR_pruning_dist=kb,\n                        MR_pruning_LD=r2,MR_reverse=MR_reverse,save_logfiles=save_logfiles\n  ))\n  try(snp<-data.frame(SNP_MRlap=res$MRcorrection$IVs))\n  try(res_c<-as.data.frame(res$MRcorrection[-4])%>%select(nsnp=m_IVs,\n                                                          beta_MRlap=corrected_effect,\n                                                          se_MRlap=corrected_effect_se,\n                                                          p_MRlap=corrected_effect_p))\n  try(res<-c(res,res_c,snp))\n  \n  try(return(res))\n}\n\n\n# clean\nclean_expo<-function(expo,pval,low_af=0.5,high_af=0.5,\n                     clump=TRUE,kb=10000,r2=0.001,LD_file=NULL,af_filter=FALSE){\n  library(TwoSampleMR)\n  dat<-subset(expo,pval.exposure<pval)\n  if(af_filter==TRUE){dat<-subset(dat,eaf.exposure<low_af|eaf.exposure>high_af)}\n  \n  if(clump==TRUE){\n    \n    if(is.null(LD_file)==TRUE){\n      dat<-clump_data(dat,clump_kb = kb,clump_r2 = r2)}\n    else{\n      library(plinkbinr)\n      plink_pathway<-get_plink_exe()\n      snp<-data.frame(rsid=dat$SNP,pval=dat$pval.exposure)\n      snp<-try(ld_clump(snp,clump_kb = kb,clump_r2 = r2,plink_bin =plink_pathway , bfile =LD_file))\n      if (\"try-error\"%in% class(snp)){return(dat)}\n      else{\n        snp<-data.frame(SNP=snp$rsid)\n        dat<-merge(snp,dat,by.x=\"SNP\",by.y='SNP')\n      }\n    }\n    \n  }\n  return(dat)\n}\n\nclean_list<-function(list,nrow=10){\n  l<-lapply(list,nrow)\n  n<-data.frame()\n  for(i in 1:length(l)){\n    if(is.null(l[[i]])==T || l[[i]]==0 )next\n    \n    n1<-data.frame(i,l[[i]])\n    n<-rbind(n,n1)\n  }\n  colnames(n)<-c('l','row')\n  n<-subset(n,row>nrow)\n  list<-list[n$l]\n  return(list)\n}\n\nclean_IV_from_outsig<-function(dat,MR_reverse=1e-03){\n  dat<-subset(dat,pval.outcome>MR_reverse)\n  return(dat)\n}\n\n\nLDSC_rg<-function(expo,outcome,an,sample_prev=NA,\n                  population_prev=NA,ld,wld,chr_filter=c(1:22),n_blocks=200){\n  id.o<-outcome$id.outcome[1]\n  id.e<-expo$id.exposure[1]\n  \n  expo<-expo%>%mutate(Z=beta.exposure/se.exposure)\n  expo<-expo%>%select(SNP=SNP,N=samplesize.exposure,Z=Z\n                      ,A1=effect_allele.exposure\n                      ,A2=other_allele.exposure)\n  expo<-as_tibble(expo)\n  \n  outcome<-outcome%>%mutate(Z=beta.outcome/se.outcome)\n  outcome<-outcome%>%select(SNP=SNP,N=samplesize.outcome,Z=Z\n                            ,A1=effect_allele.outcome\n                            ,A2=other_allele.outcome)\n  outcome<-as_tibble(outcome)\n  \n  \n  dat<-list(expo,outcome)\n  names(dat)<-c(id.e,id.o)\n  \n  rm(expo,outcome)\n  \n  \n  res<-try(ldscr::ldsc_rg(dat,ancestry = an,sample_prev=sample_prev,\n                          population_prev=population_prev,ld=ld,wld=wld,\n                          n_blocks=n_blocks,chr_filter=chr_filter))\n  \n  return(res)\n  \n}\n\n", "middle_code": "function(dat,id){\n  lid<-lapply(dat,FUN = function(x)x$id.exposure[1])\n  lid<-unlist(lid)\n  l<-c()\n  for (i in 1:length(id)) {\n    l1<-which(lid==id[i])\n    l<-c(l,l1)\n  }\n  dat<-dat[l]\n  return(dat)\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/Get_MR/1.0/Get_MR1.0.r", "library(mr.raps)\nlibrary(TwoSampleMR)\n#library(plyr)\nlibrary(dplyr)\n#library(fs) \n#library(ggplot2) \n#library(lubridate) \nlibrary(ieugwasr)\nlibrary(plinkbinr) \nlibrary(tidyr)\n#library(progress)\nlibrary(data.table)\nlibrary(MRPRESSO)\nlibrary(parallel)\n#library(foreach)\nlibrary(doParallel)\nlibrary(pbapply)\nlibrary(stringr)\nlibrary(cause)\nlibrary(vroom)\nlibrary(MungeSumstats)\n#library(GenomicFiles)\n#library(meta)\n#library(readr)\n#library(readxl)\n#library(forestploter)\nlibrary(ldscr)\nlibrary(MRlap)\n#library(meta)\n#library(forestplot)\n#library(biomaRt)\n#library(gwasglue)\n#library(coloc)\n\n# format\nformat_Mun<-function(file,source=\"finn_r8\",save_path=NULL,lift=F,ref_genome = \"hg38\",\n                     convert_ref_genome = \"hg19\"){\n  library(data.table)\n  library(MungeSumstats)\n  library(dplyr)\n  if(class(file)!=\"data.frame\"){\n  dat<-fread(file)\n  if(source==\"finn_r8\"){\n    dat<-dat%>%dplyr::select(SNP=rsids,CHR=`#chrom`,BP=pos,A1=ref,\n                             A2=alt,FRQ=af_alt,BETA=beta,\n                             SE=sebeta,P=pval)\n  }\n  }\n  dat<-as.data.frame(dat)\n  dat<-format_sumstats(dat,return_data = TRUE)\n  if(is.null(save_path)==F){setwd(save_path)}\n  dat<-fwrite(dat,paste0(file,'(Mun_format',ref_genome,').gz'))\n  te<-fs::dir_info( tempdir())\n  te<-subset(te,size>1e+8)\n  fs::file_delete(te$path)\n  if(lift==T){\n    dat <- MungeSumstats::liftover(sumstats_dt = dat, \n                                   ref_genome = ref_genome,\n                                   convert_ref_genome = convert_ref_genome)\n    dat<-fwrite(dat,paste0(file,'(Mun_format',convert_ref_genome,').gz'))\n  }\n  gc()\n}\n\nformat_getmr<-function(data,type=\"exposure\",source=\"finn_r8\"){\n  library(TwoSampleMR)\n  library(MungeSumstats)\n  \n  if(source==\"finn_r8\"){\n    data<-format_data(data,type=type,\n                      id_col = \"id\",chr_col =\"#chrom\",pos=\"pos\",\n                      snp_col = \"rsids\",beta_col = \"beta\",se_col = \"sebeta\",\n                      effect_allele_col = \"alt\",other_allele_col = \"ref\",\n                      eaf_col = \"af_alt\",phenotype_col = \"phenotype\",pval_col = \"pval\")\n  }\n  \n  \n  \n  if(source==\"ukb_nosnp\"){\n    data<-separate(data,variant,c(\"chr\",\"pos\",\"ref\",\"alt\"),sep = \":\")\n    \n    data<-dplyr::select(data,chr,pos,ref,alt,minor_AF,beta,se,pval)\n    name<-colnames(data)\n    colnames(data) <-c('CHR','BP','A1','A2','FRQ','BETA', 'SE','P')\n    \n    expo_rs_done<-format_sumstats(data,ref_genome = \"GRCh37\",return_data = TRUE)\n    \n    expo_rs_done$BP<-as.character(expo_rs_done$BP)\n    colnames(data)<-name\n    data<-merge(data,expo_rs_done,by.x=c(\"chr\",\"pos\"),by.y=c(\"CHR\",\"BP\"),all.x=TRUE)\n    \n    data<-format_data(data,type=type,\n                      samplesize_col = \"n_complete_samples\",\n                      snp_col = \"SNP\",effect_allele_col = \"alt\",\n                      other_allele_col = \"ref\",eaf_col =\"minor_AF\",\n                      beta_col=\"beta\",se_col = \"se\",pval_col = \"pval\",\n                      chr_col=\"chr\",pos_col =\"pos\",id='id',phenotype_col = 'phenotype')\n  }\n  \n  if(source==\"Mun\"){\n    data<-format_data(data,type=type,\n                      snp_col = 'SNP',\n                      chr_col = 'CHR',\n                      pos_col = 'BP',\n                      effect_allele_col = 'A2',\n                      other_allele_col = \"A1\",\n                      se_col = 'SE',\n                      beta_col= 'BETA',\n                      eaf_col = 'FRQ',\n                      id_col = 'id',\n                      phenotype_col = \"phenotype\",\n                      pval_col = \"P\"\n    )\n  }\n  \n  if(source==\"covid\"){\n    data<-format_data(data,type=type,\n                      id_col = \"id\",chr_col =\"#CHR\",pos=\"POS\",\n                      snp_col = \"rsid\",beta_col = \"all_inv_var_meta_beta\",se_col = \"all_inv_var_meta_sebeta\",\n                      effect_allele_col = \"ALT\",other_allele_col = \"REF\",\n                      eaf_col = \"all_meta_AF\",phenotype_col = \"phenotype\",\n                      ncase_col = \"all_inv_var_meta_cases\",ncontrol_col = \"all_inv_var_meta_controls\",\n                      pval_col = \"all_inv_var_meta_p\")\n  }\n  \n  if(source==\"outcome\"){\n    data<-format_data(data,type=type,\n                      id_col = \"id.outcome\",chr_col =\"chr.outcome\",pos=\"pos.outcome\",\n                      snp_col = \"SNP\",beta_col = \"beta.outcome\",se_col = \"se.outcome\",\n                      effect_allele_col = \"effect_allele.outcome\",other_allele_col = \"other_allele.outcome\",\n                      eaf_col = \"eaf.outcome\",phenotype_col = \"outcome\",\n                      samplesize_col = \"samplesize.outcome\",\n                      pval_col = \"pval.outcome\")\n    \n  }\n  if(source==\"exposure\"){\n    data<-format_data(data,type=type,\n                      id_col = \"id.exposure\",chr_col =\"chr.exposure\",pos=\"pos.exposure\",\n                      snp_col = \"SNP\",beta_col = \"beta.exposure\",se_col = \"se.exposure\",\n                      effect_allele_col = \"effect_allele.exposure\",other_allele_col = \"other_allele.exposure\",\n                      eaf_col = \"eaf.exposure\",phenotype_col = \"exposure\",\n                      samplesize_col = \"samplesize.exposure\",\n                      pval_col = \"pval.exposure\")\n    \n  }\n  \n  if(source==\"fast_ukb\"){\n    data<-format_data(data,type=type,id_col=\"id\",\n                      phenotype_col = \"phenotype\",snp_col = \"SNP\",\n                      effect_allele_col = \"A1\",other_allele_col = \"A2\",\n                      eaf_col =\"AF1\",beta_col=\"BETA\",se_col = \"SE\",\n                      pval_col = \"P\",chr_col = \"CHR\",pos_col = \"POS\")\n  }\n  \n  \n  \n  if(source==\"bac\"){\n    data<-format_data(data,type=type,id_col=\"bac\",\n                      phenotype_col = \"phenotype\",snp_col = \"rsID\",\n                      effect_allele_col = \"eff.allele\",other_allele_col = \"ref.allele\",\n                      beta_col=\"beta\",se_col = \"SE\",\n                      pval_col = \"P.weightedSumZ\",chr_col = \"chr\",pos_col = \"bp\",samplesize_col = \"N\")\n  }\n  \n  if(source==\"finn_r7\"){\n    data<-format_data(data,type=type,snp_col = \"rsids\",\n                      effect_allele_col = \"alt\",other_allele_col = \"ref\",\n                      beta_col=\"beta\",se_col = \"sebeta\",eaf_col = \"af_alt\",\n                      pval_col = \"pval\",chr_col = \"chrom\",pos_col = \"pos\")\n  }\n  return(data)\n}\n\n\nformat_trait<-function(list,short=FALSE,short_num=\"40\"){\n  for(i in 1:length(list)){\n    expo<-data.frame(exposure=list[[i]]\n                     $exposure)\n    try(expo<-separate(expo,exposure,c('a','b'),sep='\\\\|\\\\|'))\n    if(short==TRUE){try(expo$a <- substr(expo$a, 1, short_num))}\n    try(expo<-expo$a)\n    try(expo<-gsub(\":\",\"_\",expo))\n    try(expo<-gsub(\"-\",\"_\",expo))\n    try(expo<-gsub(\" \",\"_\",expo))\n    try(expo<-gsub(\",\",\"_\",expo))\n    try(expo<-gsub(\"/\",\"_\",expo))\n    list[[i]]$exposure<-expo[1]\n    \n  }\n  \n  \n  return(list)\n}\n\n# read\nread_vcf_getmr<-function(file_name,nThread = 8,type=\".gz\"){\n  name<-file_name\n  \n  for(i in 1:nrow(name)){\n    dat<-read_sumstats(paste0(\"./\",name[i]),nThread = nThread,nrow=Inf,standardise_headers = FALSE,mapping_file = sumstatsColHeaders)\n    \n    vroom_write(dat,paste0(name[i],type))\n    \n    gc()\n  }\n  print(i)\n  \n}\n\nread_easy<-function(file_name,pval=5e-08){\n  library(data.table)\n  dat<-fread(file_name)\n  dat<-subset(dat,pval.exposure<pval)\n  return(dat)\n}\n\n\n# get\nget_eaf_from_1000G<-function(dat,path,type=\"exposure\"){\n  \n  corrected_eaf_expo<-function(data_MAF){\n    effect=data_MAF$effect_allele.exposure\n    other=data_MAF$other_allele.exposure\n    A1=data_MAF$A1\n    A2=data_MAF$A2\n    MAF_num=data_MAF$MAF\n    EAF_num=1-MAF_num\n    \n    harna<-is.na(data_MAF$A1)\n    harna<-data_MAF$SNP[which(harna==T)]\n    \n    cor1<-which(data_MAF$effect_allele.exposure !=data_MAF$A1)\n    \n    \n    data_MAF$eaf.exposure=data_MAF$MAF\n    data_MAF$type=\"raw\"\n    data_MAF$eaf.exposure[cor1]=EAF_num[cor1]\n    data_MAF$type[cor1]=\"corrected\"\n    cor2<-which(data_MAF$other_allele.exposure ==data_MAF$A1)\n    cor21<-setdiff(cor2,cor1)\n    cor12<-setdiff(cor1,cor2)\n    error<-c(cor12,cor21)\n    data_MAF$eaf.exposure[error]=NA\n    data_MAF$type[error]=\"error\"\n    \n    data_MAF<-list(data_MAF=data_MAF,cor1=cor1,harna=harna,error=error)\n    \n    return(data_MAF)\n    \n  }\n  \n  corrected_eaf_out<-function(data_MAF){\n    effect=data_MAF$effect_allele.outcome\n    other=data_MAF$other_allele.outcome\n    A1=data_MAF$A1\n    A2=data_MAF$A2\n    MAF_num=data_MAF$MAF\n    EAF_num=1-MAF_num\n    \n    harna<-is.na(data_MAF$A1)\n    harna<-data_MAF$SNP[which(harna==T)]\n    \n    cor1<-which(data_MAF$effect_allele.outcome !=data_MAF$A1)\n    \n    \n    data_MAF$eaf.outcome=data_MAF$MAF\n    data_MAF$type=\"raw\"\n    data_MAF$eaf.outcome[cor1]=EAF_num[cor1]\n    data_MAF$type[cor1]=\"corrected\"\n    cor2<-which(data_MAF$other_allele.outcome ==data_MAF$A1)\n    cor21<-setdiff(cor2,cor1)\n    cor12<-setdiff(cor1,cor2)\n    error<-c(cor12,cor21)\n    data_MAF$eaf.outcome[error]=NA\n    data_MAF$type[error]=\"error\"\n    \n    data_MAF<-list(data_MAF=data_MAF,cor1=cor1,harna=harna,error=error)\n    \n    return(data_MAF)\n    \n  }\n  \n  if(type==\"exposure\" && (is.na(dat$eaf.exposure[1])==T || is.null(dat$eaf.exposure)==T)){\n    r<-nrow(dat)\n    \n    setwd(path)\n    MAF<-fread(\"fileFrequency.frq\",header = T)\n    \n    dat<-merge(dat,MAF,by.x = \"SNP\",by.y = \"SNP\",all.x = T)\n    \n    dat<-corrected_eaf_expo(dat)\n    \n    cor1<-dat$cor1\n    \n    harna<-dat$harna\n    \n    error<-dat$error\n    \n    dat<-dat$data_MAF\n    \n    print(paste0(\"一共有\",(r-length(harna)-length(error)),\"个SNP成功匹配EAF,占比\",(r-length(harna)-length(error))/r*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(cor1),\"个SNP是major allele,EAF被计算为1-MAF,在成功匹配数目中占比\",length(cor1)/(r-length(harna)-length(error))*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(harna),\"个SNP在1000G中找不到,占比\",length(harna)/r*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(error),\"个SNP在输入数据与1000G中效应列与参照列,将剔除eaf,占比\",length(error)/r*100,\"%\"))\n    \n    print(\"输出数据中的type列说明:\")\n    print(\"raw:EAF直接等于1000G里的MAF数值,因为效应列是minor allele\")\n    print('corrected:EAF等于1000G中1-MAF,因为效应列是major allele')\n    print(\"error:输入数据与1000G里面提供的数据完全不一致,比如这个SNP输入的效应列是C,参照列是G,但是1000G提供的是A-T,这种情况下,EAF会被清空(NA),当成匹配失败\")\n    \n    return(dat)\n  }\n  \n  if(type==\"outcome\" && (is.na(dat$eaf.outcome[1])==T || is.null(dat$eaf.outcome)==T)){\n    r<-nrow(dat)\n    \n    setwd(path)\n    MAF<-fread(\"fileFrequency.frq\",header = T)\n    \n    dat<-merge(dat,MAF,by.x = \"SNP\",by.y = \"SNP\",all.x = T)\n    \n    dat<-corrected_eaf_out(dat)\n    \n    cor1<-dat$cor1\n    \n    harna<-dat$harna\n    \n    error<-dat$error\n    \n    dat<-dat$data_MAF\n    \n    print(paste0(\"一共有\",(r-length(harna)-length(error)),\"个SNP成功匹配EAF,占比\",(r-length(harna)-length(error))/r*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(cor1),\"个SNP是major allele,EAF被计算为1-MAF,在成功匹配数目中占比\",length(cor1)/(r-length(harna)-length(error))*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(harna),\"个SNP在1000G找不到,占比\",length(harna)/r*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(error),\"个SNP在输入数据与1000G中效应列与参照列,将剔除eaf,占比\",length(error)/r*100,\"%\"))\n    \n    print(\"输出数据中的type列说明:\")\n    print(\"raw:EAF直接等于1000G里的MAF数值,因为效应列是minor allele\")\n    print('corrected:EAF等于1000G中1-MAF,因为效应列是major allele')\n    print(\"error:输入数据与1000G里面提供的数据完全不一致,比如这个SNP输入的效应列是C,参照列是G,但是1000G提供的是A-T,这种情况下,EAF会被清空(NA),当成匹配失败\")\n    \n    return(dat)\n  }\n  else{return(dat)}\n}\n\nget_chr_pos<-function(dat,type=\"exposure\"){\n  if(type==\"exposure\"){\n    if(is.na(dat$eaf.exposure[1])==T || is.null(dat$eaf.exposure)==T){\n      print(\"需要先运行get_eaf_from_1000G来匹配eaf,再匹配chr和pos\")\n    }\n    else{\n      dat_d<-dat%>%select(SNP,effect_allele.exposure,other_allele.exposure,eaf.exposure,beta.exposure,se.exposure,pval.exposure)\n      colnames(dat_d) <-c('SNP','A1','A2','FRQ','BETA', 'SE','P')\n      dat_d<-format_sumstats(dat_d,ref_genome = \"GRCh37\",return_data = TRUE)\n      dat_d<-format_data(dat_d,type=type,\n                         snp_col = 'SNP',\n                         chr_col = 'CHR',\n                         pos_col = 'BP',\n                         effect_allele_col = 'A1',\n                         other_allele_col = \"A2\",\n                         se_col = 'SE',\n                         beta_col= 'BETA',\n                         eaf_col = 'FRQ',\n                         pval_col = \"P\"\n      )\n      dat_d<-dat_d%>%select(SNP,chr.exposure,pos.exposure)\n      dat<-merge(dat,dat_d,by=\"SNP\",all.x=T)\n      \n      return(dat)\n    }\n  }\n  if(type==\"outcome\"){\n    if(is.na(dat$eaf.outcome[1])==T || is.null(dat$eaf.outcome)==T){\n      print(\"需要先运行get_eaf_from_1000G来匹配eaf,再匹配chr和pos\")\n    }\n    else{\n      dat_d<-dat%>%select(SNP,effect_allele.outcome,other_allele.outcome,eaf.outcome,beta.outcome,se.outcome,pval.outcome)\n      colnames(dat_d) <-c('SNP','A1','A2','FRQ','BETA', 'SE','P')\n      dat_d<-format_sumstats(dat_d,ref_genome = \"GRCh37\",return_data = TRUE)\n      dat_d<-format_data(dat_d,type=type,\n                         snp_col = 'SNP',\n                         chr_col = 'CHR',\n                         pos_col = 'BP',\n                         effect_allele_col = 'A1',\n                         other_allele_col = \"A2\",\n                         se_col = 'SE',\n                         beta_col= 'BETA',\n                         eaf_col = 'FRQ',\n                         pval_col = \"P\"\n      )\n      dat_d<-dat_d%>%select(SNP,chr.outcome,pos.outcome)\n      dat<-merge(dat,dat_d,by=\"SNP\",all.x=T)\n      \n      return(dat)\n    }\n    \n  }\n}\n\nget_f<-function(dat,F_value=10){\n  log<-is.na(dat$eaf.exposure)\n  log<-unique(log)\n  if(length(log)==1)\n  {if(log==TRUE){\n    print(\"数据不包含eaf,无法计算F统计量\")\n    return(dat)}\n  }\n  if(is.null(dat$beta.exposure[1])==T || is.na(dat$beta.exposure[1])==T){print(\"数据不包含beta,无法计算F统计量\")\n    return(dat)}\n  if(is.null(dat$se.exposure[1])==T || is.na(dat$se.exposure[1])==T){print(\"数据不包含se,无法计算F统计量\")\n    return(dat)}\n  if(is.null(dat$samplesize.exposure[1])==T || is.na(dat$samplesize.exposure[1])==T){print(\"数据不包含samplesize(样本量),无法计算F统计量\")\n    return(dat)}\n  \n  \n  if(\"FALSE\"%in%log && is.null(dat$beta.exposure[1])==F && is.na(dat$beta.exposure[1])==F && is.null(dat$se.exposure[1])==F && is.na(dat$se.exposure[1])==F && is.null(dat$samplesize.exposure[1])==F && is.na(dat$samplesize.exposure[1])==F){\n    R2<-(2*(1-dat$eaf.exposure)*dat$eaf.exposure*(dat$beta.exposure^2))/((2*(1-dat$eaf.exposure)*dat$eaf.exposure*(dat$beta.exposure^2))+(2*(1-dat$eaf.exposure)*dat$eaf.exposure*(dat$se.exposure^2)*dat$samplesize.exposure))\n    F<- (dat$samplesize.exposure-2)*R2/(1-R2)\n    dat$R2<-R2\n    dat$F<-F\n    dat<-subset(dat,F>F_value)\n    return(dat)\n  }\n}\n\n\n# MR\ncause_getmr<-function(expo,outcome,LD_file,r2=0.001,\n                        kb=10000,pval=1e-05,cl=NULL){\n  format_cause_expo<-function(dat){\n    library(cause)\n    dat<-gwas_format(dat,snp='SNP',beta_hat ='beta.exposure',\n                     se='se.exposure',A1=\"effect_allele.exposure\",\n                     A2=\"other_allele.exposure\",chrom='chr.exposure',\n                     pos=\"pos.exposure\",p_value = 'pval.exposure'\n    )\n    return(dat)\n  }\n  format_cause_out<-function(dat){\n    library(cause)\n    dat<-gwas_format(dat,snp='SNP',beta_hat ='beta.outcome',\n                     se='se.outcome',A1=\"effect_allele.outcome\",\n                     A2=\"other_allele.outcome\",chrom='chr.outcome',\n                     pos=\"pos.outcome\",p_value = 'pval.outcome'\n    )\n    return(dat)\n  }\n  sample_cause<-function(dat,num_snp){\n    set.seed(123)\n    VAR<-with(dat,sample(snp,size=num_snp,replace=FALSE))\n    return(VAR)\n  }\n  datap_cause<-function(dat){\n    dat$p1<-pnorm(abs(dat$beta_hat_1/dat$seb1),lower.tail=F)*2\n    return(dat)\n  }\n  dat_clump_cause<-function(dat){\n    for_clump<-data.frame(dat$snp,dat$p1)\n    colnames(for_clump)<-c('rsid','pval')\n    return(for_clump)\n  }\n  datap_cause<-function(dat){\n    dat$p1<-pnorm(abs(dat$beta_hat_1/dat$seb1),lower.tail=F)*2\n    return(dat)\n  }\n  ld_local<-function(dat,r2,kb,p,LD_file){\n    library(plinkbinr)\n    \n    plink_pathway<-get_plink_exe()\n    \n    dat<-ld_clump(dat,clump_r2 = r2,clump_kb = kb,\n                  clump_p = p,\n                  plink_bin =plink_pathway , bfile =LD_file)\n    \n    return(dat)\n  }\n  if(\"list\"%in%class(outcome)){\n    single_expo=T\n    single_outcome=F}\n  if(\"list\"%in%class(expo)){\n    single_outcome=T\n    single_expo=F}\n  if(single_expo==T){\n    outcome<-pblapply(outcome,FUN=format_cause_out,cl=cl)\n    expo<-format_cause_expo(expo)\n  }\n  if(single_outcome==T){\n    expo<-pblapply(expo,FUN=format_cause_expo,cl=cl)\n    outcome<-format_cause_out(outcome)\n  }\n  \n  \n  if(single_outcome==T){dat<-pblapply(expo,outcome,FUN=gwas_merge,cl=cl)}\n  if(single_expo==T){dat<-pblapply(outcome,expo,\n                                   FUN=function(outcome,exposure)gwas_merge(exposure,outcome),\n                                   cl=cl)}\n  \n  \n  VAR<-pblapply(dat,1000000,FUN=sample_cause)\n  \n  est<-foreach(i=1:length(VAR)) %do%{\n    library(cause)\n    data<-est_cause_params(dat[[i]],VAR[[i]])\n  }\n  dat<-pblapply(dat,FUN=datap_cause)\n  for_clump<-lapply(dat, dat_clump_cause)\n  clumped<-pblapply(for_clump,0.001,10000,1e-05,LD_file,FUN=ld_local)\n  top_vars<-pblapply(clumped,FUN=function(dat) return(dat$rsid))\n  cause_res<-list()\n  for(i in 1:length(dat)){\n    library(cause)\n    res<-cause(dat[[i]],est[[i]],top_vars[[i]])\n    cause_res[[i]]<-res\n    print(i)\n  }\n  cause_table<-data.frame()\n  for (i in 1:length(cause_res)){\n    res<-cause_res[[i]]\n    elpd<-res$elpd\n    elpd$p<-pnorm(-elpd$z,lower.tail = F)\n    name<-paste0('file',i)\n    elpd$file<-name\n    cause_table<-rbind(cause_table,elpd)\n  }\n  return(cause_table)\n}\n\n# RAPS\nRAPS_getmr<-function(dat,dir_figure){\n  setwd(dir_figure)\n  res<-try(mr.raps(dat,over.dispersion = TRUE))\n  if(class(res)%in%\"try-error\"){}\n  else{\n    exposure<-dat$id.exposure\n    dir_create(exposure)\n    dir_in<-paste0(dir_figure,'/',exposure)\n    setwd(dir_in)\n    #plot_name<-paste0(exposure,'raps.pdf')\n    ggsave(file='raps_plot.pdf',plot=plot(res),width=9,height=5)\n    res<-data.frame(beta.raps=res$beta.hat,se.raps=res$beta.se,\n                    eov=res$tau2.hat,se.eov=res$tau2.se,OR.raps=NA,\n                    or_lci95.raps=NA,or_uci95.raps=NA)\n    res$OR.raps<- exp(res$beta.raps)\n    res$or_lci95.raps<-exp(res$beta.raps)-(res$beta.raps*1.96)\n    res$or_uci95.raps<-exp(res$beta.raps)+(res$beta.raps*1.96)\n    res$pval.raps<-2*pnorm(abs(res$beta.raps/res$se.raps),lower.tail=F) \n    res$pval.eov<-2*pnorm(abs(res$eov/res$se.eov),lower.tail=F)\n    if(is.na(res$pval.eov)==FALSE){\n      if(res$pval.eov >0.05 ){\n        res1<-mr.raps(dat,over.dispersion = F)\n        setwd(dir_in)\n        #plot_name<-paste0(exposure,'raps.pdf')\n        ggsave(file='raps_plot.pdf',plot=plot(res1),width=9,height=5)\n        res1<-data.frame(beta.raps=res1$beta.hat,se.raps=res1$beta.se,\n                         eov=NA,se.eov=NA)\n        res1$eov<-res$eov\n        res1$se.eov<-res$se.eov\n        res1$OR.raps<- exp(res1$beta.raps)\n        res1$or_lci95.raps<-exp(res1$beta.raps)-(res1$beta.raps*1.96)\n        res1$or_uci95.raps<-exp(res1$beta.raps)+(res1$beta.raps*1.96)\n        res1$pval.raps<-2*pnorm(abs(res1$beta.raps/res1$se.raps),lower.tail=F) \n        res1$pval.eov<-2*pnorm(abs(res1$eov/res1$se.eov),lower.tail=F)\n        \n        res<-res1\n      }\n    }\n    \n    return(res)\n  }\n}\n\nmr_dircreate_base<-function(root_dir,project_name,date=NULL){  \n  library(fs)\n  dir_name<-root_dir\n  setwd(dir_name)\n  \n  if(is.null(date)==FALSE){data_u<-date}else{data_u<-Sys.Date()}\n  \n  dir_name2<-project_name\n  dir_name3<-paste0(dir_name2,data_u)\n  dir_create(dir_name3)\n  setwd(paste0(dir_name,\"/\",dir_name3))\n  dir_name4<-\"1.figure\"\n  dir_name5<-\"2.table\"\n  dir_name6<-\"3.figure of sig res\"\n  dir_name7<-\"4.snp with Fval\"\n  \n  paste<-paste0(dir_name,\"/\",dir_name3,\"/\")\n  \n  dir1<-paste0(paste,dir_name4)\n  dir.create(dir1)\n  \n  dir2<-paste0(paste,dir_name5)\n  dir.create(dir2)\n  \n  dir3<-paste0(paste,dir_name6)\n  dir.create(dir3)\n  \n  dir4<-paste0(paste,dir_name7)\n  dir.create(dir4)\n  \n  res<-list(paste=paste,dir1=dir1,dir2=dir2,dir3=dir3,dir4=dir4)\n  \n  return(res)\n}\n\n\n\n# PRESSO\nmr_Presso<-function(dat,num=10000){\n  library(TwoSampleMR)\n  library(MRPRESSO)\n  library(dplyr)\n  set.seed(123)\n  try (mr_presso_res<-mr_presso(BetaOutcome =\"beta.outcome\", BetaExposure = \"beta.exposure\", SdOutcome =\"se.outcome\", SdExposure = \"se.exposure\", \n                                OUTLIERtest = TRUE,DISTORTIONtest = TRUE, data = dat,  \n                                SignifThreshold = 0.05,NbDistribution = num))\n  return(mr_presso_res)\n  \n}\nmr_presso_pval<-function(mr_presso_res){ \n  try ( mr_presso_main<-mr_presso_res$`Main MR results`)\n  try ( mr_presso_main[3:5,]<-NA) \n  return(mr_presso_main)\n}\n\n\nmr_presso_snp<-function(mr_presso_res,mr_presso_main,dat,type=\"list\"){\n  data_re<-list()\n  if(type==\"list\"){\n    for(i in 1:length(mr_presso_res)){\n      res<-mr_presso_res$`MR-PRESSO results`[[i]]\n      main<-mr_presso_main[[i]]\n      data<-dat[[i]]\n      try(if(is.na(main[2,6])==FALSE){\n        outliers<-which(res$`Outlier Test`$Pvalue<0.05)\n        data$mr_keep[outliers]<-FALSE\n      })\n      data_re[[i]]<-data\n      names(data_re)[[i]]<-names(dat)[[i]]\n    }\n    return(data_re)\n  }\n  \n  if(type==\"data\"){\n    res<-mr_presso_res$`MR-PRESSO results`\n    main<-mr_presso_main\n    data<-dat\n    try(if(is.na(main[2,6])==FALSE){\n      outliers<-which(res$`Outlier Test`$Pvalue<0.05)\n      data$mr_keep[outliers]<-FALSE\n    })\n    return(data)\n  }\n}\n\n#MRlap\n\nmr_lap<-function(expo,outcome,ld,hm3,pval,r2,kb,MR_reverse=1e-03,save_logfiles=F){\n  expo<-expo%>%select(rsid=SNP,chr=chr.exposure,pos=pos.exposure,alt=effect_allele.exposure,\n                      ref=other_allele.exposure,N=samplesize.exposure,beta=beta.exposure,\n                      se=se.exposure)\n  expo<-as.data.frame(expo)\n  outcome<-outcome%>%select(rsid=SNP,chr=chr.outcome,pos=pos.outcome,alt=effect_allele.outcome,\n                            ref=other_allele.outcome,N=samplesize.outcome,beta=beta.outcome,\n                            se=se.outcome)\n  outcome<-as.data.frame(outcome)\n  n_expo<-expo$exposure[1]\n  n_out<-outcome$outcome[1]\n  \n  try(res<-MRlap::MRlap(exposure = expo,\n                        exposure_name = n_expo,\n                        outcome = outcome,\n                        outcome_name = n_out,\n                        ld = ld,\n                        hm3 = hm3,MR_threshold=pval,MR_pruning_dist=kb,\n                        MR_pruning_LD=r2,MR_reverse=MR_reverse,save_logfiles=save_logfiles\n  ))\n  try(snp<-data.frame(SNP_MRlap=res$MRcorrection$IVs))\n  try(res_c<-as.data.frame(res$MRcorrection[-4])%>%select(nsnp=m_IVs,\n                                                          beta_MRlap=corrected_effect,\n                                                          se_MRlap=corrected_effect_se,\n                                                          p_MRlap=corrected_effect_p))\n  try(res<-c(res,res_c,snp))\n  \n  try(return(res))\n}\n\n\n# clean\nclean_expo<-function(expo,pval,low_af=0.5,high_af=0.5,\n                     clump=TRUE,kb=10000,r2=0.001,LD_file=NULL,af_filter=FALSE){\n  library(TwoSampleMR)\n  dat<-subset(expo,pval.exposure<pval)\n  if(af_filter==TRUE){dat<-subset(dat,eaf.exposure<low_af|eaf.exposure>high_af)}\n  \n  if(clump==TRUE){\n    \n    if(is.null(LD_file)==TRUE){\n      dat<-clump_data(dat,clump_kb = kb,clump_r2 = r2)}\n    else{\n      library(plinkbinr)\n      plink_pathway<-get_plink_exe()\n      snp<-data.frame(rsid=dat$SNP,pval=dat$pval.exposure)\n      snp<-try(ld_clump(snp,clump_kb = kb,clump_r2 = r2,plink_bin =plink_pathway , bfile =LD_file))\n      if (\"try-error\"%in% class(snp)){return(dat)}\n      else{\n        snp<-data.frame(SNP=snp$rsid)\n        dat<-merge(snp,dat,by.x=\"SNP\",by.y='SNP')\n      }\n    }\n    \n  }\n  return(dat)\n}\n\nclean_list<-function(list,nrow=10){\n  l<-lapply(list,nrow)\n  n<-data.frame()\n  for(i in 1:length(l)){\n    if(is.null(l[[i]])==T || l[[i]]==0 )next\n    \n    n1<-data.frame(i,l[[i]])\n    n<-rbind(n,n1)\n  }\n  colnames(n)<-c('l','row')\n  n<-subset(n,row>nrow)\n  list<-list[n$l]\n  return(list)\n}\n\nclean_IV_from_outsig<-function(dat,MR_reverse=1e-03){\n  dat<-subset(dat,pval.outcome>MR_reverse)\n  return(dat)\n}\n\n\nLDSC_rg<-function(expo,outcome,an,sample_prev=NA,\n                  population_prev=NA,ld,wld,chr_filter=c(1:22),n_blocks=200){\n  id.o<-outcome$id.outcome[1]\n  id.e<-expo$id.exposure[1]\n  \n  expo<-expo%>%mutate(Z=beta.exposure/se.exposure)\n  expo<-expo%>%select(SNP=SNP,N=samplesize.exposure,Z=Z\n                      ,A1=effect_allele.exposure\n                      ,A2=other_allele.exposure)\n  expo<-as_tibble(expo)\n  \n  outcome<-outcome%>%mutate(Z=beta.outcome/se.outcome)\n  outcome<-outcome%>%select(SNP=SNP,N=samplesize.outcome,Z=Z\n                            ,A1=effect_allele.outcome\n                            ,A2=other_allele.outcome)\n  outcome<-as_tibble(outcome)\n  \n  \n  dat<-list(expo,outcome)\n  names(dat)<-c(id.e,id.o)\n  \n  rm(expo,outcome)\n  \n  \n  res<-try(ldscr::ldsc_rg(dat,ancestry = an,sample_prev=sample_prev,\n                          population_prev=population_prev,ld=ld,wld=wld,\n                          n_blocks=n_blocks,chr_filter=chr_filter))\n  \n  return(res)\n  \n}\n\n"], ["/Get_MR/1.0/Get_MR1.0dependence.R", "## 保证你的R版本是4.2及以上!!\ninstall.packages(\"devtools\")\nif (!require(\"BiocManager\", quietly = TRUE))\n  install.packages(\"BiocManager\")\ndevtools::install_github(\"rondolab/MR-PRESSO\")\ndevtools::install_github(\"MRCIEU/TwoSampleMR\")\ndevtools::install_github(\"explodecomputer/plinkbinr\")\ndevtools::install_github(\"mrcieu/ieugwasr\")\ndevtools::install_github(\"jean997/cause\")\nBiocManager::install(\"MungeSumstats\")\ndevtools::install_github(\"n-mounier/MRlap\")\ndevtools::install_github(\"mglev1n/ldscr\")\ninstall.packages(c('dplyr','tidyr','data.table','stringr','vroom','mr.raps','pbapply','doParallel'))\n"], ["/Get_MR/1.0/Install_Reference_Genome.r", "BiocManager::install(\"SNPlocs.Hsapiens.dbSNP155.GRCh37\")\nBiocManager::install(\"BSgenome.Hsapiens.1000genomes.hs37d5\")\nBiocManager::install(\"SNPlocs.Hsapiens.dbSNP155.GRCh38\")\nBiocManager::install(\"BSgenome.Hsapiens.NCBI.GRCh38\")\n"]], "task_instance_info": {"created_time": "2025-08-21 00:59:47", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(dat,id) {}", "code_description": "This code segment functions to: Filter elements from a collection based on identifier matching criteria, retaining only those entries that correspond to specified identification values within their metadata attributes."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nclean_GWAS_id <- function(dat, id) {\n  # Filter GWAS list to remove datasets with matching ID\n  # Args:\n  #   dat: List of GWAS datasets\n  #   id: Target GWAS ID to remove\n  \n  # Create logical filter for non-matching IDs\n  keep <- sapply(dat, function(x) {\n    if(is.data.frame(x) && \"id.exposure\" %in% names(x)) {\n      x$id.exposure[1] != id\n    } else {\n      TRUE  # Preserve non-dataframe elements\n    }\n  })\n  \n  # Return filtered list\n  return(dat[keep])\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-00-16"}, "editdistance_info": {"edit_distance": 10.2564, "calculate_time": "2025-08-21 01:00:16", "true_code_clean": "function(dat,id){\n  lid<-lapply(dat,FUN = function(x)x$id.exposure[1])\n  lid<-unlist(lid)\n  l<-c()\n  for (i in 1:length(id)) {\n    l1<-which(lid==id[i])\n    l<-c(l,l1)\n  }\n  dat<-dat[l]\n  return(dat)\n}", "predict_code_clean": "clean_GWAS_id <- function(dat, id) {\n  keep <- sapply(dat, function(x) {\n    if(is.data.frame(x) && \"id.exposure\" %in% names(x)) {\n      x$id.exposure[1] != id\n    } else {\n      TRUE  \n    }\n  })\n  return(dat[keep])\n}"}}
{"repo_name": "Get_MR", "file_name": "/Get_MR/2.0/Get_MR2.0.r", "inference_info": {"prefix_code": "library(mr.raps)\nlibrary(TwoSampleMR)\nlibrary(dplyr)\nlibrary(fs) \nlibrary(ieugwasr)\nlibrary(plinkbinr) \nlibrary(tidyr)\nlibrary(data.table)\nlibrary(MRPRESSO)\nlibrary(parallel)\nlibrary(doParallel)\nlibrary(pbapply)\nlibrary(stringr)\nlibrary(cause)\nlibrary(vroom)\nlibrary(MungeSumstats)\nlibrary(ldscr)\nlibrary(MRlap)\n\n\nselect<-dplyr::select\nmcl<-makeCluster\n\n\n## 2.0更新内容\n\nclean<-function(list,clean_0=FALSE){\n  \n  l<-pblapply(list,class)\n  ll<-c()\n  for(i in 1:length(l)){\n    if(l[[i]][1]%in% \"try-error\"){}\n    else{ll<-c(ll,i)}\n  }\n  list<-list[ll]\n  \n  if(clean_0==TRUE){\n    list<-Filter(function(x) nrow(x)!=0, list)\n  }\n  return(list)\n}\n\nget_rsid<-function(chr,pos,version='hg38'){\n  library(biomaRt)\n  dat<-data.frame(CHR=chr,start=pos,end=pos)\n  if(version==\"hg38\"){\n    ver<-listEnsemblArchives()%>%subset(name!='Ensembl GRCh37')\n    ur<-ver$url[1]\n    snp_mart <- useEnsembl(biomart=\"ENSEMBL_MART_SNP\", \n                           host=ur, \n                           dataset=\"hsapiens_snp\")\n    position <- apply(dat, 1, paste, collapse = \":\")\n    res<-getBM(attributes = c('refsnp_id', 'allele', 'chrom_start'), \n               filters = 'chromosomal_region', \n               values = position, \n               mart = snp_mart)\n  }\n  if(version==\"hg19\"){\n    snp_mart <- useEnsembl(biomart=\"ENSEMBL_MART_SNP\", \n                           host=\"https://grch37.ensembl.org\", \n                           dataset=\"hsapiens_snp\")\n    position <- apply(dat, 1, paste, collapse = \":\")\n    res<-getBM(attributes = c('refsnp_id', 'allele', 'chrom_start'), \n               filters = 'chromosomal_region', \n               values = position, \n               mart = snp_mart)\n  }\n  \n  return(res)\n}\n\nget_exposure = function(id,pval=5e-08,r2=0.001,kb=10000) {\n  library(TwoSampleMR)\n  dat<-try(data.frame(extract_instruments(id,p1=pval,clump = T,p2=1,r2=r2,kb=kb)))\n  if ('try-error'%in%class(dat))   {\n    dat=NA\n  }\n  return(dat)\n}\n\nget_outcome=function(id,expo){\n  library(TwoSampleMR)\n  dat<-try(data.frame(extract_outcome_data(expo$SNP,id,proxies = F,maf_threshold=0.4)))\n  if ('try-error'%in%class(dat))   {\n    dat=NA\n  }\n  \n  try( return(dat))\n}\n\nget_ao<-function(a=NULL){\n  ao<-available_outcomes()\n  ao<-separate(ao,id,c(\"a\",\"b\",\"c\"),sep=\"-\",remove = FALSE)\n  if(is.null(a)==F){ao<-subset(ao,a==a)}\n  return(ao)\n}\n\nget_exposure_wrong_num<-function(list){\n  res<-is.na(list)\n  num=0\n  foreach (i=1:length(res))%do%{\n    if(res[i]==TRUE) num=num+1\n  }\n  return(num)\n}\n\nclean_outcome_from_exposure<-function(expo,outcome){\n  snp<-lapply(expo,FUN=function(x)data.frame(SNP=x$SNP))\n  snp<-bind_rows(snp)\n  snp<-data.frame(SNP=unique(snp$SNP))\n  outcome_adj<-merge(outcome,snp)\n  return(outcome_adj)\n}\n\nclean_GWAS<-function(list,clean=c(\"bbj\",\"eqtl\")){\n  clean_GWAS_logit<-function(dat,clean){\n    id<-dat$id.exposure[1]\n    id<-as.data.frame(id)\n    id<-separate(id,\"id\",c('a','b','c'),sep = \"-\")\n    if(id$a==clean){\n      return(data.frame(lg=1))\n    }\n    else(return(data.frame(lg=0)))\n  }\n  print(\"正在获取指定数据集信息\")\n  for(i in 1:length(clean)){\n  lg<-pblapply(list,clean[i],FUN=clean_GWAS_logit)\n  \n  lg<-bind_rows(lg)\n  \n  list<-list[which(lg$lg==0)]\n  }\n  return(list)\n  \n}\n\n\n\ncyclemr<-function(dat,cl_num,type=\"list\"){\nclean<-function(list,clean_0=FALSE){\n  \n  l<-pblapply(list,class)\n  ll<-c()\n  for(i in 1:length(l)){\n    if(l[[i]][1]%in% \"try-error\"){}\n    else{ll<-c(ll,i)}\n  }\n  list<-list[ll]\n  \n  if(clean_0==TRUE){\n    list<-Filter(function(x) nrow(x)!=0, list)\n  }\n  return(list)\n}\n  # base mr\n  mr_base<-function(dat){\n    library(TwoSampleMR)\n    library(dplyr)\n    try(mr<-mr(dat) )\n    try(mr<-dplyr::select(mr,id.exposure,id.outcome,method,nsnp,b,se,pval)) \n    try(mr_OR<-generate_odds_ratios(mr_res = mr(dat)))\n    try(mr_OR<-dplyr::select(mr_OR,id.exposure,id.outcome,method,nsnp,b,se,pval,lo_ci,up_ci,or, or_lci95,or_uci95))\n    try(mr_OR<-dplyr::rename(mr_OR,b.OR=\"b\",se.OR=\"se\",pval.OR=\"pval\"))\n    try( mr_p_OR<-merge(mr,mr_OR))\n    try(return(mr_p_OR))\n  }\n  \n  mr_egger<-function(dat){\n    library(TwoSampleMR)\n    library(dplyr)\n    mr_egger<-mr_pleiotropy_test(dat) \n    try( mr_egger<-dplyr::select(mr_egger,id.exposure,id.outcome,egger_intercept,se,pval))\n    try( mr_egger<-dplyr::rename(mr_egger,se.egger=\"se\",pval.egger=\"pval\"))\n    try( mr_egger[2:5,]<-NA) \n    try( return(mr_egger))\n  }\n  \n  mr_test<-function(dat){\n    library(TwoSampleMR)\n    library(dplyr)\n    mr_heterogeneity<-mr_heterogeneity(dat)\n    try (mr_heterogeneity<-dplyr::select(mr_heterogeneity,id.exposure,id.outcome,method,Q, Q_df,Q_pval))\n    try( mr_heterogeneity<-dplyr::rename(mr_heterogeneity,method.he=\"method\"))\n    try (mr_heterogeneity[3:5,]<-NA )\n    try( return(mr_heterogeneity))\n  }\n  \n  # presso\n  cycle_presso<-function(dat){\n    library(TwoSampleMR)\n    library(MRPRESSO)\n    library(dplyr) \n    nsnp_filter=6\n    try (mr_presso_res<-mr_presso(BetaOutcome =\"beta.outcome\", BetaExposure = \"beta.exposure\", SdOutcome =\"se.outcome\", SdExposure = \"se.exposure\", \n                                  OUTLIERtest = TRUE,DISTORTIONtest = TRUE, data = dat,  \n                                  SignifThreshold = 0.05))\n    try ( mr_presso_main<-mr_presso_res$`Main MR results`)\n    try(mr_presso_main)\n    try ( mr_presso_main[3:5,]<-NA)\n    try(  return(mr_presso_main))\n  }\n  \n  mr_Presso<-function(dat,num=10000){\n    library(TwoSampleMR)\n    library(MRPRESSO)\n    library(dplyr)\n    \n    nsnp_filter=6\n    set.seed(123)\n    try (mr_presso_res<-mr_presso(BetaOutcome =\"beta.outcome\", BetaExposure = \"beta.exposure\", SdOutcome =\"se.outcome\", SdExposure = \"se.exposure\", \n                                  OUTLIERtest = TRUE,DISTORTIONtest = TRUE, data = dat,  \n                                  SignifThreshold = 0.05,NbDistribution = num))\n    return(mr_presso_res)\n    \n  }\n  mr_presso_pval<-function(mr_presso_res){ \n    try ( mr_presso_main<-mr_presso_res$`Main MR results`)\n    try ( mr_presso_main[3:5,]<-NA) \n    return(mr_presso_main)\n  }\n  \n  \n  mr_presso_snp<-function(mr_presso_res,mr_presso_main,dat,type=\"list\"){\n    data_re<-list()\n    if(type==\"list\"){\n      for(i in 1:length(mr_presso_res)){\n        res<-mr_presso_res$`MR-PRESSO results`[[i]]\n        main<-mr_presso_main[[i]]\n        data<-dat[[i]]\n        try(if(is.na(main[2,6])==FALSE){\n          outliers<-which(res$`Outlier Test`$Pvalue<0.05)\n          data$mr_keep[outliers]<-FALSE\n        })\n        data_re[[i]]<-data\n        names(data_re)[[i]]<-names(dat)[[i]]\n      }\n      return(data_re)\n    }\n    \n    if(type==\"data\"){\n      res<-mr_presso_res$`MR-PRESSO results`\n      main<-mr_presso_main\n      data<-dat\n      try(if(is.na(main[2,6])==FALSE){\n        outliers<-which(res$`Outlier Test`$Pvalue<0.05)\n        data$mr_keep[outliers]<-FALSE\n      })\n      return(data)\n    }\n  }\n  bind_basemr<-function(base.res,egger.res,test.res){\n    res_all<-data.frame()\n    for(i in 1:nrow(base.res)){\n      if(i%%5==1){\n        id<-base.res$id.exposure[i]\n        num.bg<-which(egger.res$id.exposure==id)\n        num.end<-num.bg+4\n        res<-cbind(base.res[i:(i+4),],egger.res[num.bg:num.end,3:5])\n        num.bg<-which(test.res$id.exposure==id)[1]\n        num.end<-num.bg+4\n        res<-cbind(res,test.res[num.bg:num.end,3:6])\n        res_all<-rbind(res_all,res)\n      }\n    }\n    return(res_all)\n  }\n  \n  if(type==\"list\"){\n    cl <- makeCluster(cl_num) \n    \n    base.res<-pblapply(dat, FUN=mr_base,cl=cl)\n    \n    egger.res<-pblapply(dat, FUN=mr_egger)\n    \n    test.res<-pblapply(dat,FUN=mr_test)\n    \n    stopCluster(cl)\n    \n    base.res<-clean(base.res)\n    \n    egger.res<-clean(egger.res)\n    \n    test.res<-clean(test.res)\n    \n    base.res<-bind_rows (base.res)\n    \n    base.res<-subset(base.res,nsnp>2) ## 防止出现wald ratio,导致错误\n    \n    egger.res<-bind_rows (egger.res)\n    \n    test.res<-bind_rows (test.res)\n    \n    res_all<-bind_basemr(base.res,egger.res,test.res)\n    \n  }\n  \n  if(type==\"data\"){\n    \n    presso_res<-mr_Presso(dat,10000)\n    \n    presso_pval<-mr_presso_pval(presso_res)\n    \n    dat_aj<-mr_presso_snp(presso_res,presso_pval,dat,\"data\")\n    \n    base.res<-mr_base(dat)\n    \n    egger.res<-mr_egger(dat)\n    \n    test.res<-mr_test(dat)\n    \n    base.res<-bind_rows (base.res)\n    \n    res_all<-cbind(base.res,presso_pval,egger.res,test.res)\n  }\n  \n  return(res_all)\n}\n\n\nbind_basemr<-function(base.res,egger.res,test.res){\n  res_all<-data.frame()\n  for(i in 1:nrow(base.res)){\n    if(i%%5==1){\n      id<-base.res$id.exposure[i]\n      num.bg<-which(egger.res$id.exposure==id)\n      num.end<-num.bg+4\n      res<-cbind(base.res[i:(i+4),],egger.res[num.bg:num.end,3:5])\n      num.bg<-which(test.res$id.exposure==id)[1]\n      num.end<-num.bg+4\n      res<-cbind(res,test.res[num.bg:num.end,3:6])\n      res_all<-rbind(res_all,res)\n    }\n  }\n  return(res_all)\n}\n\n\nbind_pressomr<-", "suffix_code": "\n\n\nbind_trait<-function(res_all,ao){\n  res_all<-data.frame(trait=NA,res_all)\n  for(i in 1:nrow(res_all)){\n    try( num<-which(ao$id==res_all$id.exposure[i]))\n    try( res_all$trait[i]<-ao$trait[num])\n  }\n  return(res_all)\n}\n\nbind_trait_outcome<-function(res_all,ao){\n  res_all<-data.frame(trait=NA,res_all)\n  for(i in 1:nrow(res_all)){\n    num<-which(ao$id==res_all$id.outcome[i])\n    res_all$trait[i]<-ao$trait[num]\n  }\n  return(res_all)\n}\n\nclean_cl<-function(){\n  cl<<-makeCluster(1)\n  stopCluster(cl)\n  gc()\n}\n\nclean_GWAS_id<-function(dat,id){\n  lid<-lapply(dat,FUN = function(x)x$id.exposure[1])\n  lid<-unlist(lid)\n  l<-c()\n  for (i in 1:length(id)) {\n    l1<-which(lid==id[i])\n    l<-c(l,l1)\n  }\n  dat<-dat[l]\n  return(dat)\n}\n\n\n## 1.0内容\n# format\nformat_Mun<-function(file,source=\"finn_r8\",save_path=NULL,lift=F,ref_genome = \"hg38\",\n                     convert_ref_genome = \"hg19\"){\n  library(data.table)\n  library(MungeSumstats)\n  library(dplyr)\n  if(class(file)!=\"data.frame\"){\n    dat<-fread(file)\n    if(source==\"finn_r8\"){\n      dat<-dat%>%dplyr::select(SNP=rsids,CHR=`#chrom`,BP=pos,A1=ref,\n                               A2=alt,FRQ=af_alt,BETA=beta,\n                               SE=sebeta,P=pval)\n    }\n  }\n  dat<-as.data.frame(dat)\n  dat<-format_sumstats(dat,return_data = TRUE)\n  if(is.null(save_path)==F){setwd(save_path)}\n  dat<-fwrite(dat,paste0(file,'(Mun_format',ref_genome,').gz'))\n  te<-fs::dir_info( tempdir())\n  te<-subset(te,size>1e+8)\n  fs::file_delete(te$path)\n  if(lift==T){\n    dat <- MungeSumstats::liftover(sumstats_dt = dat, \n                                   ref_genome = ref_genome,\n                                   convert_ref_genome = convert_ref_genome)\n    dat<-fwrite(dat,paste0(file,'(Mun_format',convert_ref_genome,').gz'))\n  }\n  gc()\n}\n\nformat_cyclemr<-function(data,type=\"exposure\",source=\"finn_r8\"){\n  library(TwoSampleMR)\n  library(MungeSumstats)\n  \n  if(source==\"finn_r8\"){\n    data<-format_data(data,type=type,\n                      id_col = \"id\",chr_col =\"#chrom\",pos=\"pos\",\n                      snp_col = \"rsids\",beta_col = \"beta\",se_col = \"sebeta\",\n                      effect_allele_col = \"alt\",other_allele_col = \"ref\",\n                      eaf_col = \"af_alt\",phenotype_col = \"phenotype\",pval_col = \"pval\")\n  }\n  \n  \n  \n  if(source==\"ukb_nosnp\"){\n    data<-separate(data,variant,c(\"chr\",\"pos\",\"ref\",\"alt\"),sep = \":\")\n    \n    data<-dplyr::select(data,chr,pos,ref,alt,minor_AF,beta,se,pval)\n    name<-colnames(data)\n    colnames(data) <-c('CHR','BP','A1','A2','FRQ','BETA', 'SE','P')\n    \n    expo_rs_done<-format_sumstats(data,ref_genome = \"GRCh37\",return_data = TRUE)\n    \n    expo_rs_done$BP<-as.character(expo_rs_done$BP)\n    colnames(data)<-name\n    data<-merge(data,expo_rs_done,by.x=c(\"chr\",\"pos\"),by.y=c(\"CHR\",\"BP\"),all.x=TRUE)\n    \n    data<-format_data(data,type=type,\n                      samplesize_col = \"n_complete_samples\",\n                      snp_col = \"SNP\",effect_allele_col = \"alt\",\n                      other_allele_col = \"ref\",eaf_col =\"minor_AF\",\n                      beta_col=\"beta\",se_col = \"se\",pval_col = \"pval\",\n                      chr_col=\"chr\",pos_col =\"pos\",id='id',phenotype_col = 'phenotype')\n  }\n  \n  if(source==\"Mun\"){\n    data<-format_data(data,type=type,\n                      snp_col = 'SNP',\n                      chr_col = 'CHR',\n                      pos_col = 'BP',\n                      effect_allele_col = 'A2',\n                      other_allele_col = \"A1\",\n                      se_col = 'SE',\n                      beta_col= 'BETA',\n                      eaf_col = 'FRQ',\n                      id_col = 'id',\n                      phenotype_col = \"phenotype\",\n                      pval_col = \"P\"\n    )\n  }\n  \n  if(source==\"covid\"){\n    data<-format_data(data,type=type,\n                      id_col = \"id\",chr_col =\"#CHR\",pos=\"POS\",\n                      snp_col = \"rsid\",beta_col = \"all_inv_var_meta_beta\",se_col = \"all_inv_var_meta_sebeta\",\n                      effect_allele_col = \"ALT\",other_allele_col = \"REF\",\n                      eaf_col = \"all_meta_AF\",phenotype_col = \"phenotype\",\n                      ncase_col = \"all_inv_var_meta_cases\",ncontrol_col = \"all_inv_var_meta_controls\",\n                      pval_col = \"all_inv_var_meta_p\")\n  }\n  \n  if(source==\"outcome\"){\n    data<-format_data(data,type=type,\n                      id_col = \"id.outcome\",chr_col =\"chr.outcome\",pos=\"pos.outcome\",\n                      snp_col = \"SNP\",beta_col = \"beta.outcome\",se_col = \"se.outcome\",\n                      effect_allele_col = \"effect_allele.outcome\",other_allele_col = \"other_allele.outcome\",\n                      eaf_col = \"eaf.outcome\",phenotype_col = \"outcome\",\n                      samplesize_col = \"samplesize.outcome\",\n                      pval_col = \"pval.outcome\")\n    \n  }\n  if(source==\"exposure\"){\n    data<-format_data(data,type=type,\n                      id_col = \"id.exposure\",chr_col =\"chr.exposure\",pos=\"pos.exposure\",\n                      snp_col = \"SNP\",beta_col = \"beta.exposure\",se_col = \"se.exposure\",\n                      effect_allele_col = \"effect_allele.exposure\",other_allele_col = \"other_allele.exposure\",\n                      eaf_col = \"eaf.exposure\",phenotype_col = \"exposure\",\n                      samplesize_col = \"samplesize.exposure\",\n                      pval_col = \"pval.exposure\")\n    \n  }\n  \n  if(source==\"fast_ukb\"){\n    data<-format_data(data,type=type,id_col=\"id\",\n                      phenotype_col = \"phenotype\",snp_col = \"SNP\",\n                      effect_allele_col = \"A1\",other_allele_col = \"A2\",\n                      eaf_col =\"AF1\",beta_col=\"BETA\",se_col = \"SE\",\n                      pval_col = \"P\",chr_col = \"CHR\",pos_col = \"POS\")\n  }\n  \n  \n  \n  if(source==\"bac\"){\n    data<-format_data(data,type=type,id_col=\"bac\",\n                      phenotype_col = \"phenotype\",snp_col = \"rsID\",\n                      effect_allele_col = \"eff.allele\",other_allele_col = \"ref.allele\",\n                      beta_col=\"beta\",se_col = \"SE\",\n                      pval_col = \"P.weightedSumZ\",chr_col = \"chr\",pos_col = \"bp\",samplesize_col = \"N\")\n  }\n  \n  if(source==\"finn_r7\"){\n    data<-format_data(data,type=type,snp_col = \"rsids\",\n                      effect_allele_col = \"alt\",other_allele_col = \"ref\",\n                      beta_col=\"beta\",se_col = \"sebeta\",eaf_col = \"af_alt\",\n                      pval_col = \"pval\",chr_col = \"chrom\",pos_col = \"pos\")\n  }\n  return(data)\n}\n\n\nformat_trait<-function(list,short=FALSE,short_num=\"40\"){\n  for(i in 1:length(list)){\n    expo<-data.frame(exposure=list[[i]]\n                     $exposure)\n    try(expo<-separate(expo,exposure,c('a','b'),sep='\\\\|\\\\|'))\n    if(short==TRUE){try(expo$a <- substr(expo$a, 1, short_num))}\n    try(expo<-expo$a)\n    try(expo<-gsub(\":\",\"_\",expo))\n    try(expo<-gsub(\"-\",\"_\",expo))\n    try(expo<-gsub(\" \",\"_\",expo))\n    try(expo<-gsub(\",\",\"_\",expo))\n    try(expo<-gsub(\"/\",\"_\",expo))\n    list[[i]]$exposure<-expo[1]\n    \n  }\n  \n  \n  return(list)\n}\n\n# read\nread_vcf_getmr<-function(file_name,nThread = 8,type=\".gz\"){\n  name<-file_name\n  \n  for(i in 1:nrow(name)){\n    dat<-read_sumstats(paste0(\"./\",name[i]),nThread = nThread,nrow=Inf,standardise_headers = FALSE,mapping_file = sumstatsColHeaders)\n    \n    vroom_write(dat,paste0(name[i],type))\n    \n    gc()\n  }\n  print(i)\n  \n}\n\nread_easy<-function(file_name,pval=5e-08){\n  library(data.table)\n  dat<-fread(file_name)\n  dat<-subset(dat,pval.exposure<pval)\n  return(dat)\n}\n\n\n# get\nget_eaf_from_1000G<-function(dat,path,type=\"exposure\"){\n  \n  corrected_eaf_expo<-function(data_MAF){\n    effect=data_MAF$effect_allele.exposure\n    other=data_MAF$other_allele.exposure\n    A1=data_MAF$A1\n    A2=data_MAF$A2\n    MAF_num=data_MAF$MAF\n    EAF_num=1-MAF_num\n    \n    harna<-is.na(data_MAF$A1)\n    harna<-data_MAF$SNP[which(harna==T)]\n    \n    cor1<-which(data_MAF$effect_allele.exposure !=data_MAF$A1)\n    \n    \n    data_MAF$eaf.exposure=data_MAF$MAF\n    data_MAF$type=\"raw\"\n    data_MAF$eaf.exposure[cor1]=EAF_num[cor1]\n    data_MAF$type[cor1]=\"corrected\"\n    cor2<-which(data_MAF$other_allele.exposure ==data_MAF$A1)\n    cor21<-setdiff(cor2,cor1)\n    cor12<-setdiff(cor1,cor2)\n    error<-c(cor12,cor21)\n    data_MAF$eaf.exposure[error]=NA\n    data_MAF$type[error]=\"error\"\n    \n    data_MAF<-list(data_MAF=data_MAF,cor1=cor1,harna=harna,error=error)\n    \n    return(data_MAF)\n    \n  }\n  \n  corrected_eaf_out<-function(data_MAF){\n    effect=data_MAF$effect_allele.outcome\n    other=data_MAF$other_allele.outcome\n    A1=data_MAF$A1\n    A2=data_MAF$A2\n    MAF_num=data_MAF$MAF\n    EAF_num=1-MAF_num\n    \n    harna<-is.na(data_MAF$A1)\n    harna<-data_MAF$SNP[which(harna==T)]\n    \n    cor1<-which(data_MAF$effect_allele.outcome !=data_MAF$A1)\n    \n    \n    data_MAF$eaf.outcome=data_MAF$MAF\n    data_MAF$type=\"raw\"\n    data_MAF$eaf.outcome[cor1]=EAF_num[cor1]\n    data_MAF$type[cor1]=\"corrected\"\n    cor2<-which(data_MAF$other_allele.outcome ==data_MAF$A1)\n    cor21<-setdiff(cor2,cor1)\n    cor12<-setdiff(cor1,cor2)\n    error<-c(cor12,cor21)\n    data_MAF$eaf.outcome[error]=NA\n    data_MAF$type[error]=\"error\"\n    \n    data_MAF<-list(data_MAF=data_MAF,cor1=cor1,harna=harna,error=error)\n    \n    return(data_MAF)\n    \n  }\n  \n  if(type==\"exposure\" && (is.na(dat$eaf.exposure[1])==T || is.null(dat$eaf.exposure)==T)){\n    r<-nrow(dat)\n    \n    setwd(path)\n    MAF<-fread(\"fileFrequency.frq\",header = T)\n    \n    dat<-merge(dat,MAF,by.x = \"SNP\",by.y = \"SNP\",all.x = T)\n    \n    dat<-corrected_eaf_expo(dat)\n    \n    cor1<-dat$cor1\n    \n    harna<-dat$harna\n    \n    error<-dat$error\n    \n    dat<-dat$data_MAF\n    \n    print(paste0(\"一共有\",(r-length(harna)-length(error)),\"个SNP成功匹配EAF,占比\",(r-length(harna)-length(error))/r*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(cor1),\"个SNP是major allele,EAF被计算为1-MAF,在成功匹配数目中占比\",length(cor1)/(r-length(harna)-length(error))*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(harna),\"个SNP在1000G中找不到,占比\",length(harna)/r*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(error),\"个SNP在输入数据与1000G中效应列与参照列,将剔除eaf,占比\",length(error)/r*100,\"%\"))\n    \n    print(\"输出数据中的type列说明:\")\n    print(\"raw:EAF直接等于1000G里的MAF数值,因为效应列是minor allele\")\n    print('corrected:EAF等于1000G中1-MAF,因为效应列是major allele')\n    print(\"error:输入数据与1000G里面提供的数据完全不一致,比如这个SNP输入的效应列是C,参照列是G,但是1000G提供的是A-T,这种情况下,EAF会被清空(NA),当成匹配失败\")\n    \n    return(dat)\n  }\n  \n  if(type==\"outcome\" && (is.na(dat$eaf.outcome[1])==T || is.null(dat$eaf.outcome)==T)){\n    r<-nrow(dat)\n    \n    setwd(path)\n    MAF<-fread(\"fileFrequency.frq\",header = T)\n    \n    dat<-merge(dat,MAF,by.x = \"SNP\",by.y = \"SNP\",all.x = T)\n    \n    dat<-corrected_eaf_out(dat)\n    \n    cor1<-dat$cor1\n    \n    harna<-dat$harna\n    \n    error<-dat$error\n    \n    dat<-dat$data_MAF\n    \n    print(paste0(\"一共有\",(r-length(harna)-length(error)),\"个SNP成功匹配EAF,占比\",(r-length(harna)-length(error))/r*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(cor1),\"个SNP是major allele,EAF被计算为1-MAF,在成功匹配数目中占比\",length(cor1)/(r-length(harna)-length(error))*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(harna),\"个SNP在1000G找不到,占比\",length(harna)/r*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(error),\"个SNP在输入数据与1000G中效应列与参照列,将剔除eaf,占比\",length(error)/r*100,\"%\"))\n    \n    print(\"输出数据中的type列说明:\")\n    print(\"raw:EAF直接等于1000G里的MAF数值,因为效应列是minor allele\")\n    print('corrected:EAF等于1000G中1-MAF,因为效应列是major allele')\n    print(\"error:输入数据与1000G里面提供的数据完全不一致,比如这个SNP输入的效应列是C,参照列是G,但是1000G提供的是A-T,这种情况下,EAF会被清空(NA),当成匹配失败\")\n    \n    return(dat)\n  }\n  else{return(dat)}\n}\n\nget_chr_pos<-function(dat,type=\"exposure\"){\n  if(type==\"exposure\"){\n    if(is.na(dat$eaf.exposure[1])==T || is.null(dat$eaf.exposure)==T){\n      print(\"需要先运行get_eaf_from_1000G来匹配eaf,再匹配chr和pos\")\n    }\n    else{\n      dat_d<-dat%>%select(SNP,effect_allele.exposure,other_allele.exposure,eaf.exposure,beta.exposure,se.exposure,pval.exposure)\n      colnames(dat_d) <-c('SNP','A1','A2','FRQ','BETA', 'SE','P')\n      dat_d<-format_sumstats(dat_d,ref_genome = \"GRCh37\",return_data = TRUE)\n      dat_d<-format_data(dat_d,type=type,\n                         snp_col = 'SNP',\n                         chr_col = 'CHR',\n                         pos_col = 'BP',\n                         effect_allele_col = 'A1',\n                         other_allele_col = \"A2\",\n                         se_col = 'SE',\n                         beta_col= 'BETA',\n                         eaf_col = 'FRQ',\n                         pval_col = \"P\"\n      )\n      dat_d<-dat_d%>%select(SNP,chr.exposure,pos.exposure)\n      dat<-merge(dat,dat_d,by=\"SNP\",all.x=T)\n      \n      return(dat)\n    }\n  }\n  if(type==\"outcome\"){\n    if(is.na(dat$eaf.outcome[1])==T || is.null(dat$eaf.outcome)==T){\n      print(\"需要先运行get_eaf_from_1000G来匹配eaf,再匹配chr和pos\")\n    }\n    else{\n      dat_d<-dat%>%select(SNP,effect_allele.outcome,other_allele.outcome,eaf.outcome,beta.outcome,se.outcome,pval.outcome)\n      colnames(dat_d) <-c('SNP','A1','A2','FRQ','BETA', 'SE','P')\n      dat_d<-format_sumstats(dat_d,ref_genome = \"GRCh37\",return_data = TRUE)\n      dat_d<-format_data(dat_d,type=type,\n                         snp_col = 'SNP',\n                         chr_col = 'CHR',\n                         pos_col = 'BP',\n                         effect_allele_col = 'A1',\n                         other_allele_col = \"A2\",\n                         se_col = 'SE',\n                         beta_col= 'BETA',\n                         eaf_col = 'FRQ',\n                         pval_col = \"P\"\n      )\n      dat_d<-dat_d%>%select(SNP,chr.outcome,pos.outcome)\n      dat<-merge(dat,dat_d,by=\"SNP\",all.x=T)\n      \n      return(dat)\n    }\n    \n  }\n}\n\nget_f<-function(dat,F_value=10){\n  log<-is.na(dat$eaf.exposure)\n  log<-unique(log)\n  if(length(log)==1)\n  {if(log==TRUE){\n    print(\"数据不包含eaf,无法计算F统计量\")\n    return(dat)}\n  }\n  if(is.null(dat$beta.exposure[1])==T || is.na(dat$beta.exposure[1])==T){print(\"数据不包含beta,无法计算F统计量\")\n    return(dat)}\n  if(is.null(dat$se.exposure[1])==T || is.na(dat$se.exposure[1])==T){print(\"数据不包含se,无法计算F统计量\")\n    return(dat)}\n  if(is.null(dat$samplesize.exposure[1])==T || is.na(dat$samplesize.exposure[1])==T){print(\"数据不包含samplesize(样本量),无法计算F统计量\")\n    return(dat)}\n  \n  \n  if(\"FALSE\"%in%log && is.null(dat$beta.exposure[1])==F && is.na(dat$beta.exposure[1])==F && is.null(dat$se.exposure[1])==F && is.na(dat$se.exposure[1])==F && is.null(dat$samplesize.exposure[1])==F && is.na(dat$samplesize.exposure[1])==F){\n    R2<-(2*(1-dat$eaf.exposure)*dat$eaf.exposure*(dat$beta.exposure^2))/((2*(1-dat$eaf.exposure)*dat$eaf.exposure*(dat$beta.exposure^2))+(2*(1-dat$eaf.exposure)*dat$eaf.exposure*(dat$se.exposure^2)*dat$samplesize.exposure))\n    F<- (dat$samplesize.exposure-2)*R2/(1-R2)\n    dat$R2<-R2\n    dat$F<-F\n    dat<-subset(dat,F>F_value)\n    return(dat)\n  }\n}\n\n\n# MR\ncause_getmr<-function(expo,outcome,LD_file,r2=0.001,\n                      kb=10000,pval=1e-05,cl=NULL){\n  format_cause_expo<-function(dat){\n    library(cause)\n    dat<-gwas_format(dat,snp='SNP',beta_hat ='beta.exposure',\n                     se='se.exposure',A1=\"effect_allele.exposure\",\n                     A2=\"other_allele.exposure\",chrom='chr.exposure',\n                     pos=\"pos.exposure\",p_value = 'pval.exposure'\n    )\n    return(dat)\n  }\n  format_cause_out<-function(dat){\n    library(cause)\n    dat<-gwas_format(dat,snp='SNP',beta_hat ='beta.outcome',\n                     se='se.outcome',A1=\"effect_allele.outcome\",\n                     A2=\"other_allele.outcome\",chrom='chr.outcome',\n                     pos=\"pos.outcome\",p_value = 'pval.outcome'\n    )\n    return(dat)\n  }\n  sample_cause<-function(dat,num_snp){\n    set.seed(123)\n    VAR<-with(dat,sample(snp,size=num_snp,replace=FALSE))\n    return(VAR)\n  }\n  datap_cause<-function(dat){\n    dat$p1<-pnorm(abs(dat$beta_hat_1/dat$seb1),lower.tail=F)*2\n    return(dat)\n  }\n  dat_clump_cause<-function(dat){\n    for_clump<-data.frame(dat$snp,dat$p1)\n    colnames(for_clump)<-c('rsid','pval')\n    return(for_clump)\n  }\n  datap_cause<-function(dat){\n    dat$p1<-pnorm(abs(dat$beta_hat_1/dat$seb1),lower.tail=F)*2\n    return(dat)\n  }\n  ld_local<-function(dat,r2,kb,p,LD_file){\n    library(plinkbinr)\n    \n    plink_pathway<-get_plink_exe()\n    \n    dat<-ld_clump(dat,clump_r2 = r2,clump_kb = kb,\n                  clump_p = p,\n                  plink_bin =plink_pathway , bfile =LD_file)\n    \n    return(dat)\n  }\n  if(\"list\"%in%class(outcome)){\n    single_expo=T\n    single_outcome=F}\n  if(\"list\"%in%class(expo)){\n    single_outcome=T\n    single_expo=F}\n  if(single_expo==T){\n    outcome<-pblapply(outcome,FUN=format_cause_out,cl=cl)\n    expo<-format_cause_expo(expo)\n  }\n  if(single_outcome==T){\n    expo<-pblapply(expo,FUN=format_cause_expo,cl=cl)\n    outcome<-format_cause_out(outcome)\n  }\n  \n  \n  if(single_outcome==T){dat<-pblapply(expo,outcome,FUN=gwas_merge,cl=cl)}\n  if(single_expo==T){dat<-pblapply(outcome,expo,\n                                   FUN=function(outcome,exposure)gwas_merge(exposure,outcome),\n                                   cl=cl)}\n  \n  \n  VAR<-pblapply(dat,1000000,FUN=sample_cause)\n  \n  est<-foreach(i=1:length(VAR)) %do%{\n    library(cause)\n    data<-est_cause_params(dat[[i]],VAR[[i]])\n  }\n  dat<-pblapply(dat,FUN=datap_cause)\n  for_clump<-lapply(dat, dat_clump_cause)\n  clumped<-pblapply(for_clump,0.001,10000,1e-05,LD_file,FUN=ld_local)\n  top_vars<-pblapply(clumped,FUN=function(dat) return(dat$rsid))\n  cause_res<-list()\n  for(i in 1:length(dat)){\n    library(cause)\n    res<-cause(dat[[i]],est[[i]],top_vars[[i]])\n    cause_res[[i]]<-res\n    print(i)\n  }\n  cause_table<-data.frame()\n  for (i in 1:length(cause_res)){\n    res<-cause_res[[i]]\n    elpd<-res$elpd\n    elpd$p<-pnorm(-elpd$z,lower.tail = F)\n    name<-paste0('file',i)\n    elpd$file<-name\n    cause_table<-rbind(cause_table,elpd)\n  }\n  return(cause_table)\n}\n\n# RAPS\nRAPS_getmr<-function(dat,dir_figure){\n  setwd(dir_figure)\n  res<-try(mr.raps(dat,over.dispersion = TRUE))\n  if(class(res)%in%\"try-error\"){}\n  else{\n    exposure<-dat$id.exposure\n    dir_create(exposure)\n    dir_in<-paste0(dir_figure,'/',exposure)\n    setwd(dir_in)\n    #plot_name<-paste0(exposure,'raps.pdf')\n    ggsave(file='raps_plot.pdf',plot=plot(res),width=9,height=5)\n    res<-data.frame(beta.raps=res$beta.hat,se.raps=res$beta.se,\n                    eov=res$tau2.hat,se.eov=res$tau2.se,OR.raps=NA,\n                    or_lci95.raps=NA,or_uci95.raps=NA)\n    res$OR.raps<- exp(res$beta.raps)\n    res$or_lci95.raps<-exp(res$beta.raps)-(res$beta.raps*1.96)\n    res$or_uci95.raps<-exp(res$beta.raps)+(res$beta.raps*1.96)\n    res$pval.raps<-2*pnorm(abs(res$beta.raps/res$se.raps),lower.tail=F) \n    res$pval.eov<-2*pnorm(abs(res$eov/res$se.eov),lower.tail=F)\n    if(is.na(res$pval.eov)==FALSE){\n      if(res$pval.eov >0.05 ){\n        res1<-mr.raps(dat,over.dispersion = F)\n        setwd(dir_in)\n        #plot_name<-paste0(exposure,'raps.pdf')\n        ggsave(file='raps_plot.pdf',plot=plot(res1),width=9,height=5)\n        res1<-data.frame(beta.raps=res1$beta.hat,se.raps=res1$beta.se,\n                         eov=NA,se.eov=NA)\n        res1$eov<-res$eov\n        res1$se.eov<-res$se.eov\n        res1$OR.raps<- exp(res1$beta.raps)\n        res1$or_lci95.raps<-exp(res1$beta.raps)-(res1$beta.raps*1.96)\n        res1$or_uci95.raps<-exp(res1$beta.raps)+(res1$beta.raps*1.96)\n        res1$pval.raps<-2*pnorm(abs(res1$beta.raps/res1$se.raps),lower.tail=F) \n        res1$pval.eov<-2*pnorm(abs(res1$eov/res1$se.eov),lower.tail=F)\n        \n        res<-res1\n      }\n    }\n    \n    return(res)\n  }\n}\n\nmr_dircreate_base<-function(root_dir,project_name,date=NULL){  \n  library(fs)\n  dir_name<-root_dir\n  setwd(dir_name)\n  \n  if(is.null(date)==FALSE){data_u<-date}else{data_u<-Sys.Date()}\n  \n  dir_name2<-project_name\n  dir_name3<-paste0(dir_name2,data_u)\n  dir_create(dir_name3)\n  setwd(paste0(dir_name,\"/\",dir_name3))\n  dir_name4<-\"1.figure\"\n  dir_name5<-\"2.table\"\n  dir_name6<-\"3.figure of sig res\"\n  dir_name7<-\"4.snp with Fval\"\n  \n  paste<-paste0(dir_name,\"/\",dir_name3,\"/\")\n  \n  dir1<-paste0(paste,dir_name4)\n  dir.create(dir1)\n  \n  dir2<-paste0(paste,dir_name5)\n  dir.create(dir2)\n  \n  dir3<-paste0(paste,dir_name6)\n  dir.create(dir3)\n  \n  dir4<-paste0(paste,dir_name7)\n  dir.create(dir4)\n  \n  res<-list(paste=paste,dir1=dir1,dir2=dir2,dir3=dir3,dir4=dir4)\n  \n  return(res)\n}\n\n\n\n# PRESSO\nmr_Presso<-function(dat,num=10000){\n  library(TwoSampleMR)\n  library(MRPRESSO)\n  library(dplyr)\n  \n  nsnp_filter=6\n  set.seed(123)\n  try (mr_presso_res<-mr_presso(BetaOutcome =\"beta.outcome\", BetaExposure = \"beta.exposure\", SdOutcome =\"se.outcome\", SdExposure = \"se.exposure\", \n                                OUTLIERtest = TRUE,DISTORTIONtest = TRUE, data = dat,  \n                                SignifThreshold = 0.05,NbDistribution = num))\n  return(mr_presso_res)\n  \n}\nmr_presso_pval<-function(mr_presso_res){ \n  try ( mr_presso_main<-mr_presso_res$`Main MR results`)\n  try ( mr_presso_main[3:5,]<-NA) \n  return(mr_presso_main)\n}\n\n\nmr_presso_snp<-function(mr_presso_res,mr_presso_main,dat,type=\"list\"){\n  data_re<-list()\n  if(type==\"list\"){\n    for(i in 1:length(mr_presso_res)){\n      res<-mr_presso_res[[i]]\n      main<-mr_presso_main[[i]]\n      data<-dat[[i]]\n      try(if(is.na(main[2,6])==FALSE){\n        outliers<-which(res$`MR-PRESSO results`$`Outlier Test`$Pvalue<0.05)\n        data$mr_keep[outliers]<-FALSE\n      })\n      data_re[[i]]<-data\n      names(data_re)[[i]]<-names(dat)[[i]]\n    }\n    return(data_re)\n  }\n  \n  if(type==\"data\"){\n    res<-mr_presso_res$`MR-PRESSO results`\n    main<-mr_presso_main\n    data<-dat\n    try(if(is.na(main[2,6])==FALSE){\n      outliers<-which(res$`MR-PRESSO results`$`Outlier Test`$Pvalue<0.05)\n      data$mr_keep[outliers]<-FALSE\n    })\n    return(data)\n  }\n}\n\n#MRlap\n\nmr_lap<-function(expo,outcome,ld,hm3,pval,r2,kb,MR_reverse=1e-03,save_logfiles=F){\n  expo<-expo%>%select(rsid=SNP,chr=chr.exposure,pos=pos.exposure,alt=effect_allele.exposure,\n                      ref=other_allele.exposure,N=samplesize.exposure,beta=beta.exposure,\n                      se=se.exposure)\n  expo<-as.data.frame(expo)\n  outcome<-outcome%>%select(rsid=SNP,chr=chr.outcome,pos=pos.outcome,alt=effect_allele.outcome,\n                            ref=other_allele.outcome,N=samplesize.outcome,beta=beta.outcome,\n                            se=se.outcome)\n  outcome<-as.data.frame(outcome)\n  n_expo<-expo$exposure[1]\n  n_out<-outcome$outcome[1]\n  \n  try(res<-MRlap::MRlap(exposure = expo,\n                        exposure_name = n_expo,\n                        outcome = outcome,\n                        outcome_name = n_out,\n                        ld = ld,\n                        hm3 = hm3,MR_threshold=pval,MR_pruning_dist=kb,\n                        MR_pruning_LD=r2,MR_reverse=MR_reverse,save_logfiles=save_logfiles\n  ))\n  try(snp<-data.frame(SNP_MRlap=res$MRcorrection$IVs))\n  try(res_c<-as.data.frame(res$MRcorrection[-4])%>%select(nsnp=m_IVs,\n                                                          beta_MRlap=corrected_effect,\n                                                          se_MRlap=corrected_effect_se,\n                                                          p_MRlap=corrected_effect_p))\n  try(res<-c(res,res_c,snp))\n  \n  try(return(res))\n}\n\n\n# clean\nclean_expo<-function(expo,pval,low_af=0.5,high_af=0.5,\n                     clump=TRUE,kb=10000,r2=0.001,LD_file=NULL,af_filter=FALSE){\n  library(TwoSampleMR)\n  dat<-subset(expo,pval.exposure<pval)\n  if(af_filter==TRUE){dat<-subset(dat,eaf.exposure<low_af|eaf.exposure>high_af)}\n  \n  if(clump==TRUE){\n    \n    if(is.null(LD_file)==TRUE){\n      dat<-clump_data(dat,clump_kb = kb,clump_r2 = r2)}\n    else{\n      library(plinkbinr)\n      plink_pathway<-get_plink_exe()\n      snp<-data.frame(rsid=dat$SNP,pval=dat$pval.exposure)\n      snp<-try(ld_clump(snp,clump_kb = kb,clump_r2 = r2,plink_bin =plink_pathway , bfile =LD_file))\n      if (\"try-error\"%in% class(snp)){return(dat)}\n      else{\n        snp<-data.frame(SNP=snp$rsid)\n        dat<-merge(snp,dat,by.x=\"SNP\",by.y='SNP')\n      }\n    }\n    \n  }\n  return(dat)\n}\n\nclean_list<-function(list,nrow=10){\n  l<-lapply(list,nrow)\n  n<-data.frame()\n  for(i in 1:length(l)){\n    if(is.null(l[[i]])==T || l[[i]]==0 )next\n    \n    n1<-data.frame(i,l[[i]])\n    n<-rbind(n,n1)\n  }\n  colnames(n)<-c('l','row')\n  n<-subset(n,row>nrow)\n  list<-list[n$l]\n  return(list)\n}\n\nclean_IV_from_outsig<-function(dat,MR_reverse=1e-03){\n  dat<-subset(dat,pval.outcome>MR_reverse)\n  return(dat)\n}\n\n\nLDSC_rg<-function(expo,outcome,an,sample_prev=NA,\n                  population_prev=NA,ld,wld,chr_filter=c(1:22),n_blocks=200){\n  id.o<-outcome$id.outcome[1]\n  id.e<-expo$id.exposure[1]\n  \n  expo<-expo%>%mutate(Z=beta.exposure/se.exposure)\n  expo<-expo%>%select(SNP=SNP,N=samplesize.exposure,Z=Z\n                      ,A1=effect_allele.exposure\n                      ,A2=other_allele.exposure)\n  expo<-as_tibble(expo)\n  \n  outcome<-outcome%>%mutate(Z=beta.outcome/se.outcome)\n  outcome<-outcome%>%select(SNP=SNP,N=samplesize.outcome,Z=Z\n                            ,A1=effect_allele.outcome\n                            ,A2=other_allele.outcome)\n  outcome<-as_tibble(outcome)\n  \n  \n  dat<-list(expo,outcome)\n  names(dat)<-c(id.e,id.o)\n  \n  rm(expo,outcome)\n  \n  \n  res<-try(ldscr::ldsc_rg(dat,ancestry = an,sample_prev=sample_prev,\n                          population_prev=population_prev,ld=ld,wld=wld,\n                          n_blocks=n_blocks,chr_filter=chr_filter))\n  \n  return(res)\n  \n}\n\n", "middle_code": "function(base_res,presso_pval,egger_res,test_res){\n  presso_id<-names(presso_pval)\n  presso_pval<-bind_rows(presso_pval)\n  base_res<-bind_rows(base_res)\n  egger_res<-bind_rows(egger_res)\n  test_res<-bind_rows(test_res)\n  res_all<-data.frame()\n  for(i in 1:nrow(base_res)){\n    if(i%%5==1){\n      id<-base_res$id.exposure[i]\n      num.bg<-5*(which(presso_id==id)[1]-1)+1\n      num.end<-num.bg+4\n      res<-cbind(base_res[i:(i+4),],presso_pval[num.bg:num.end,2:6])\n      num.bg<-which(egger_res$id.exposure==id)\n      num.end<-num.bg+4\n      res<-cbind(res,egger_res[num.bg:num.end,3:5])\n      num.bg<-which(test_res$id.exposure==id)[1]\n      num.end<-num.bg+4\n      res<-cbind(res,test_res[num.bg:num.end,3:6])\n      res_all<-rbind(res_all,res)\n    }\n  }\n  return(res_all)\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/Get_MR/1.0/Get_MR1.0.r", "library(mr.raps)\nlibrary(TwoSampleMR)\n#library(plyr)\nlibrary(dplyr)\n#library(fs) \n#library(ggplot2) \n#library(lubridate) \nlibrary(ieugwasr)\nlibrary(plinkbinr) \nlibrary(tidyr)\n#library(progress)\nlibrary(data.table)\nlibrary(MRPRESSO)\nlibrary(parallel)\n#library(foreach)\nlibrary(doParallel)\nlibrary(pbapply)\nlibrary(stringr)\nlibrary(cause)\nlibrary(vroom)\nlibrary(MungeSumstats)\n#library(GenomicFiles)\n#library(meta)\n#library(readr)\n#library(readxl)\n#library(forestploter)\nlibrary(ldscr)\nlibrary(MRlap)\n#library(meta)\n#library(forestplot)\n#library(biomaRt)\n#library(gwasglue)\n#library(coloc)\n\n# format\nformat_Mun<-function(file,source=\"finn_r8\",save_path=NULL,lift=F,ref_genome = \"hg38\",\n                     convert_ref_genome = \"hg19\"){\n  library(data.table)\n  library(MungeSumstats)\n  library(dplyr)\n  if(class(file)!=\"data.frame\"){\n  dat<-fread(file)\n  if(source==\"finn_r8\"){\n    dat<-dat%>%dplyr::select(SNP=rsids,CHR=`#chrom`,BP=pos,A1=ref,\n                             A2=alt,FRQ=af_alt,BETA=beta,\n                             SE=sebeta,P=pval)\n  }\n  }\n  dat<-as.data.frame(dat)\n  dat<-format_sumstats(dat,return_data = TRUE)\n  if(is.null(save_path)==F){setwd(save_path)}\n  dat<-fwrite(dat,paste0(file,'(Mun_format',ref_genome,').gz'))\n  te<-fs::dir_info( tempdir())\n  te<-subset(te,size>1e+8)\n  fs::file_delete(te$path)\n  if(lift==T){\n    dat <- MungeSumstats::liftover(sumstats_dt = dat, \n                                   ref_genome = ref_genome,\n                                   convert_ref_genome = convert_ref_genome)\n    dat<-fwrite(dat,paste0(file,'(Mun_format',convert_ref_genome,').gz'))\n  }\n  gc()\n}\n\nformat_getmr<-function(data,type=\"exposure\",source=\"finn_r8\"){\n  library(TwoSampleMR)\n  library(MungeSumstats)\n  \n  if(source==\"finn_r8\"){\n    data<-format_data(data,type=type,\n                      id_col = \"id\",chr_col =\"#chrom\",pos=\"pos\",\n                      snp_col = \"rsids\",beta_col = \"beta\",se_col = \"sebeta\",\n                      effect_allele_col = \"alt\",other_allele_col = \"ref\",\n                      eaf_col = \"af_alt\",phenotype_col = \"phenotype\",pval_col = \"pval\")\n  }\n  \n  \n  \n  if(source==\"ukb_nosnp\"){\n    data<-separate(data,variant,c(\"chr\",\"pos\",\"ref\",\"alt\"),sep = \":\")\n    \n    data<-dplyr::select(data,chr,pos,ref,alt,minor_AF,beta,se,pval)\n    name<-colnames(data)\n    colnames(data) <-c('CHR','BP','A1','A2','FRQ','BETA', 'SE','P')\n    \n    expo_rs_done<-format_sumstats(data,ref_genome = \"GRCh37\",return_data = TRUE)\n    \n    expo_rs_done$BP<-as.character(expo_rs_done$BP)\n    colnames(data)<-name\n    data<-merge(data,expo_rs_done,by.x=c(\"chr\",\"pos\"),by.y=c(\"CHR\",\"BP\"),all.x=TRUE)\n    \n    data<-format_data(data,type=type,\n                      samplesize_col = \"n_complete_samples\",\n                      snp_col = \"SNP\",effect_allele_col = \"alt\",\n                      other_allele_col = \"ref\",eaf_col =\"minor_AF\",\n                      beta_col=\"beta\",se_col = \"se\",pval_col = \"pval\",\n                      chr_col=\"chr\",pos_col =\"pos\",id='id',phenotype_col = 'phenotype')\n  }\n  \n  if(source==\"Mun\"){\n    data<-format_data(data,type=type,\n                      snp_col = 'SNP',\n                      chr_col = 'CHR',\n                      pos_col = 'BP',\n                      effect_allele_col = 'A2',\n                      other_allele_col = \"A1\",\n                      se_col = 'SE',\n                      beta_col= 'BETA',\n                      eaf_col = 'FRQ',\n                      id_col = 'id',\n                      phenotype_col = \"phenotype\",\n                      pval_col = \"P\"\n    )\n  }\n  \n  if(source==\"covid\"){\n    data<-format_data(data,type=type,\n                      id_col = \"id\",chr_col =\"#CHR\",pos=\"POS\",\n                      snp_col = \"rsid\",beta_col = \"all_inv_var_meta_beta\",se_col = \"all_inv_var_meta_sebeta\",\n                      effect_allele_col = \"ALT\",other_allele_col = \"REF\",\n                      eaf_col = \"all_meta_AF\",phenotype_col = \"phenotype\",\n                      ncase_col = \"all_inv_var_meta_cases\",ncontrol_col = \"all_inv_var_meta_controls\",\n                      pval_col = \"all_inv_var_meta_p\")\n  }\n  \n  if(source==\"outcome\"){\n    data<-format_data(data,type=type,\n                      id_col = \"id.outcome\",chr_col =\"chr.outcome\",pos=\"pos.outcome\",\n                      snp_col = \"SNP\",beta_col = \"beta.outcome\",se_col = \"se.outcome\",\n                      effect_allele_col = \"effect_allele.outcome\",other_allele_col = \"other_allele.outcome\",\n                      eaf_col = \"eaf.outcome\",phenotype_col = \"outcome\",\n                      samplesize_col = \"samplesize.outcome\",\n                      pval_col = \"pval.outcome\")\n    \n  }\n  if(source==\"exposure\"){\n    data<-format_data(data,type=type,\n                      id_col = \"id.exposure\",chr_col =\"chr.exposure\",pos=\"pos.exposure\",\n                      snp_col = \"SNP\",beta_col = \"beta.exposure\",se_col = \"se.exposure\",\n                      effect_allele_col = \"effect_allele.exposure\",other_allele_col = \"other_allele.exposure\",\n                      eaf_col = \"eaf.exposure\",phenotype_col = \"exposure\",\n                      samplesize_col = \"samplesize.exposure\",\n                      pval_col = \"pval.exposure\")\n    \n  }\n  \n  if(source==\"fast_ukb\"){\n    data<-format_data(data,type=type,id_col=\"id\",\n                      phenotype_col = \"phenotype\",snp_col = \"SNP\",\n                      effect_allele_col = \"A1\",other_allele_col = \"A2\",\n                      eaf_col =\"AF1\",beta_col=\"BETA\",se_col = \"SE\",\n                      pval_col = \"P\",chr_col = \"CHR\",pos_col = \"POS\")\n  }\n  \n  \n  \n  if(source==\"bac\"){\n    data<-format_data(data,type=type,id_col=\"bac\",\n                      phenotype_col = \"phenotype\",snp_col = \"rsID\",\n                      effect_allele_col = \"eff.allele\",other_allele_col = \"ref.allele\",\n                      beta_col=\"beta\",se_col = \"SE\",\n                      pval_col = \"P.weightedSumZ\",chr_col = \"chr\",pos_col = \"bp\",samplesize_col = \"N\")\n  }\n  \n  if(source==\"finn_r7\"){\n    data<-format_data(data,type=type,snp_col = \"rsids\",\n                      effect_allele_col = \"alt\",other_allele_col = \"ref\",\n                      beta_col=\"beta\",se_col = \"sebeta\",eaf_col = \"af_alt\",\n                      pval_col = \"pval\",chr_col = \"chrom\",pos_col = \"pos\")\n  }\n  return(data)\n}\n\n\nformat_trait<-function(list,short=FALSE,short_num=\"40\"){\n  for(i in 1:length(list)){\n    expo<-data.frame(exposure=list[[i]]\n                     $exposure)\n    try(expo<-separate(expo,exposure,c('a','b'),sep='\\\\|\\\\|'))\n    if(short==TRUE){try(expo$a <- substr(expo$a, 1, short_num))}\n    try(expo<-expo$a)\n    try(expo<-gsub(\":\",\"_\",expo))\n    try(expo<-gsub(\"-\",\"_\",expo))\n    try(expo<-gsub(\" \",\"_\",expo))\n    try(expo<-gsub(\",\",\"_\",expo))\n    try(expo<-gsub(\"/\",\"_\",expo))\n    list[[i]]$exposure<-expo[1]\n    \n  }\n  \n  \n  return(list)\n}\n\n# read\nread_vcf_getmr<-function(file_name,nThread = 8,type=\".gz\"){\n  name<-file_name\n  \n  for(i in 1:nrow(name)){\n    dat<-read_sumstats(paste0(\"./\",name[i]),nThread = nThread,nrow=Inf,standardise_headers = FALSE,mapping_file = sumstatsColHeaders)\n    \n    vroom_write(dat,paste0(name[i],type))\n    \n    gc()\n  }\n  print(i)\n  \n}\n\nread_easy<-function(file_name,pval=5e-08){\n  library(data.table)\n  dat<-fread(file_name)\n  dat<-subset(dat,pval.exposure<pval)\n  return(dat)\n}\n\n\n# get\nget_eaf_from_1000G<-function(dat,path,type=\"exposure\"){\n  \n  corrected_eaf_expo<-function(data_MAF){\n    effect=data_MAF$effect_allele.exposure\n    other=data_MAF$other_allele.exposure\n    A1=data_MAF$A1\n    A2=data_MAF$A2\n    MAF_num=data_MAF$MAF\n    EAF_num=1-MAF_num\n    \n    harna<-is.na(data_MAF$A1)\n    harna<-data_MAF$SNP[which(harna==T)]\n    \n    cor1<-which(data_MAF$effect_allele.exposure !=data_MAF$A1)\n    \n    \n    data_MAF$eaf.exposure=data_MAF$MAF\n    data_MAF$type=\"raw\"\n    data_MAF$eaf.exposure[cor1]=EAF_num[cor1]\n    data_MAF$type[cor1]=\"corrected\"\n    cor2<-which(data_MAF$other_allele.exposure ==data_MAF$A1)\n    cor21<-setdiff(cor2,cor1)\n    cor12<-setdiff(cor1,cor2)\n    error<-c(cor12,cor21)\n    data_MAF$eaf.exposure[error]=NA\n    data_MAF$type[error]=\"error\"\n    \n    data_MAF<-list(data_MAF=data_MAF,cor1=cor1,harna=harna,error=error)\n    \n    return(data_MAF)\n    \n  }\n  \n  corrected_eaf_out<-function(data_MAF){\n    effect=data_MAF$effect_allele.outcome\n    other=data_MAF$other_allele.outcome\n    A1=data_MAF$A1\n    A2=data_MAF$A2\n    MAF_num=data_MAF$MAF\n    EAF_num=1-MAF_num\n    \n    harna<-is.na(data_MAF$A1)\n    harna<-data_MAF$SNP[which(harna==T)]\n    \n    cor1<-which(data_MAF$effect_allele.outcome !=data_MAF$A1)\n    \n    \n    data_MAF$eaf.outcome=data_MAF$MAF\n    data_MAF$type=\"raw\"\n    data_MAF$eaf.outcome[cor1]=EAF_num[cor1]\n    data_MAF$type[cor1]=\"corrected\"\n    cor2<-which(data_MAF$other_allele.outcome ==data_MAF$A1)\n    cor21<-setdiff(cor2,cor1)\n    cor12<-setdiff(cor1,cor2)\n    error<-c(cor12,cor21)\n    data_MAF$eaf.outcome[error]=NA\n    data_MAF$type[error]=\"error\"\n    \n    data_MAF<-list(data_MAF=data_MAF,cor1=cor1,harna=harna,error=error)\n    \n    return(data_MAF)\n    \n  }\n  \n  if(type==\"exposure\" && (is.na(dat$eaf.exposure[1])==T || is.null(dat$eaf.exposure)==T)){\n    r<-nrow(dat)\n    \n    setwd(path)\n    MAF<-fread(\"fileFrequency.frq\",header = T)\n    \n    dat<-merge(dat,MAF,by.x = \"SNP\",by.y = \"SNP\",all.x = T)\n    \n    dat<-corrected_eaf_expo(dat)\n    \n    cor1<-dat$cor1\n    \n    harna<-dat$harna\n    \n    error<-dat$error\n    \n    dat<-dat$data_MAF\n    \n    print(paste0(\"一共有\",(r-length(harna)-length(error)),\"个SNP成功匹配EAF,占比\",(r-length(harna)-length(error))/r*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(cor1),\"个SNP是major allele,EAF被计算为1-MAF,在成功匹配数目中占比\",length(cor1)/(r-length(harna)-length(error))*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(harna),\"个SNP在1000G中找不到,占比\",length(harna)/r*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(error),\"个SNP在输入数据与1000G中效应列与参照列,将剔除eaf,占比\",length(error)/r*100,\"%\"))\n    \n    print(\"输出数据中的type列说明:\")\n    print(\"raw:EAF直接等于1000G里的MAF数值,因为效应列是minor allele\")\n    print('corrected:EAF等于1000G中1-MAF,因为效应列是major allele')\n    print(\"error:输入数据与1000G里面提供的数据完全不一致,比如这个SNP输入的效应列是C,参照列是G,但是1000G提供的是A-T,这种情况下,EAF会被清空(NA),当成匹配失败\")\n    \n    return(dat)\n  }\n  \n  if(type==\"outcome\" && (is.na(dat$eaf.outcome[1])==T || is.null(dat$eaf.outcome)==T)){\n    r<-nrow(dat)\n    \n    setwd(path)\n    MAF<-fread(\"fileFrequency.frq\",header = T)\n    \n    dat<-merge(dat,MAF,by.x = \"SNP\",by.y = \"SNP\",all.x = T)\n    \n    dat<-corrected_eaf_out(dat)\n    \n    cor1<-dat$cor1\n    \n    harna<-dat$harna\n    \n    error<-dat$error\n    \n    dat<-dat$data_MAF\n    \n    print(paste0(\"一共有\",(r-length(harna)-length(error)),\"个SNP成功匹配EAF,占比\",(r-length(harna)-length(error))/r*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(cor1),\"个SNP是major allele,EAF被计算为1-MAF,在成功匹配数目中占比\",length(cor1)/(r-length(harna)-length(error))*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(harna),\"个SNP在1000G找不到,占比\",length(harna)/r*100,\"%\"))\n    \n    print(paste0(\"一共有\",length(error),\"个SNP在输入数据与1000G中效应列与参照列,将剔除eaf,占比\",length(error)/r*100,\"%\"))\n    \n    print(\"输出数据中的type列说明:\")\n    print(\"raw:EAF直接等于1000G里的MAF数值,因为效应列是minor allele\")\n    print('corrected:EAF等于1000G中1-MAF,因为效应列是major allele')\n    print(\"error:输入数据与1000G里面提供的数据完全不一致,比如这个SNP输入的效应列是C,参照列是G,但是1000G提供的是A-T,这种情况下,EAF会被清空(NA),当成匹配失败\")\n    \n    return(dat)\n  }\n  else{return(dat)}\n}\n\nget_chr_pos<-function(dat,type=\"exposure\"){\n  if(type==\"exposure\"){\n    if(is.na(dat$eaf.exposure[1])==T || is.null(dat$eaf.exposure)==T){\n      print(\"需要先运行get_eaf_from_1000G来匹配eaf,再匹配chr和pos\")\n    }\n    else{\n      dat_d<-dat%>%select(SNP,effect_allele.exposure,other_allele.exposure,eaf.exposure,beta.exposure,se.exposure,pval.exposure)\n      colnames(dat_d) <-c('SNP','A1','A2','FRQ','BETA', 'SE','P')\n      dat_d<-format_sumstats(dat_d,ref_genome = \"GRCh37\",return_data = TRUE)\n      dat_d<-format_data(dat_d,type=type,\n                         snp_col = 'SNP',\n                         chr_col = 'CHR',\n                         pos_col = 'BP',\n                         effect_allele_col = 'A1',\n                         other_allele_col = \"A2\",\n                         se_col = 'SE',\n                         beta_col= 'BETA',\n                         eaf_col = 'FRQ',\n                         pval_col = \"P\"\n      )\n      dat_d<-dat_d%>%select(SNP,chr.exposure,pos.exposure)\n      dat<-merge(dat,dat_d,by=\"SNP\",all.x=T)\n      \n      return(dat)\n    }\n  }\n  if(type==\"outcome\"){\n    if(is.na(dat$eaf.outcome[1])==T || is.null(dat$eaf.outcome)==T){\n      print(\"需要先运行get_eaf_from_1000G来匹配eaf,再匹配chr和pos\")\n    }\n    else{\n      dat_d<-dat%>%select(SNP,effect_allele.outcome,other_allele.outcome,eaf.outcome,beta.outcome,se.outcome,pval.outcome)\n      colnames(dat_d) <-c('SNP','A1','A2','FRQ','BETA', 'SE','P')\n      dat_d<-format_sumstats(dat_d,ref_genome = \"GRCh37\",return_data = TRUE)\n      dat_d<-format_data(dat_d,type=type,\n                         snp_col = 'SNP',\n                         chr_col = 'CHR',\n                         pos_col = 'BP',\n                         effect_allele_col = 'A1',\n                         other_allele_col = \"A2\",\n                         se_col = 'SE',\n                         beta_col= 'BETA',\n                         eaf_col = 'FRQ',\n                         pval_col = \"P\"\n      )\n      dat_d<-dat_d%>%select(SNP,chr.outcome,pos.outcome)\n      dat<-merge(dat,dat_d,by=\"SNP\",all.x=T)\n      \n      return(dat)\n    }\n    \n  }\n}\n\nget_f<-function(dat,F_value=10){\n  log<-is.na(dat$eaf.exposure)\n  log<-unique(log)\n  if(length(log)==1)\n  {if(log==TRUE){\n    print(\"数据不包含eaf,无法计算F统计量\")\n    return(dat)}\n  }\n  if(is.null(dat$beta.exposure[1])==T || is.na(dat$beta.exposure[1])==T){print(\"数据不包含beta,无法计算F统计量\")\n    return(dat)}\n  if(is.null(dat$se.exposure[1])==T || is.na(dat$se.exposure[1])==T){print(\"数据不包含se,无法计算F统计量\")\n    return(dat)}\n  if(is.null(dat$samplesize.exposure[1])==T || is.na(dat$samplesize.exposure[1])==T){print(\"数据不包含samplesize(样本量),无法计算F统计量\")\n    return(dat)}\n  \n  \n  if(\"FALSE\"%in%log && is.null(dat$beta.exposure[1])==F && is.na(dat$beta.exposure[1])==F && is.null(dat$se.exposure[1])==F && is.na(dat$se.exposure[1])==F && is.null(dat$samplesize.exposure[1])==F && is.na(dat$samplesize.exposure[1])==F){\n    R2<-(2*(1-dat$eaf.exposure)*dat$eaf.exposure*(dat$beta.exposure^2))/((2*(1-dat$eaf.exposure)*dat$eaf.exposure*(dat$beta.exposure^2))+(2*(1-dat$eaf.exposure)*dat$eaf.exposure*(dat$se.exposure^2)*dat$samplesize.exposure))\n    F<- (dat$samplesize.exposure-2)*R2/(1-R2)\n    dat$R2<-R2\n    dat$F<-F\n    dat<-subset(dat,F>F_value)\n    return(dat)\n  }\n}\n\n\n# MR\ncause_getmr<-function(expo,outcome,LD_file,r2=0.001,\n                        kb=10000,pval=1e-05,cl=NULL){\n  format_cause_expo<-function(dat){\n    library(cause)\n    dat<-gwas_format(dat,snp='SNP',beta_hat ='beta.exposure',\n                     se='se.exposure',A1=\"effect_allele.exposure\",\n                     A2=\"other_allele.exposure\",chrom='chr.exposure',\n                     pos=\"pos.exposure\",p_value = 'pval.exposure'\n    )\n    return(dat)\n  }\n  format_cause_out<-function(dat){\n    library(cause)\n    dat<-gwas_format(dat,snp='SNP',beta_hat ='beta.outcome',\n                     se='se.outcome',A1=\"effect_allele.outcome\",\n                     A2=\"other_allele.outcome\",chrom='chr.outcome',\n                     pos=\"pos.outcome\",p_value = 'pval.outcome'\n    )\n    return(dat)\n  }\n  sample_cause<-function(dat,num_snp){\n    set.seed(123)\n    VAR<-with(dat,sample(snp,size=num_snp,replace=FALSE))\n    return(VAR)\n  }\n  datap_cause<-function(dat){\n    dat$p1<-pnorm(abs(dat$beta_hat_1/dat$seb1),lower.tail=F)*2\n    return(dat)\n  }\n  dat_clump_cause<-function(dat){\n    for_clump<-data.frame(dat$snp,dat$p1)\n    colnames(for_clump)<-c('rsid','pval')\n    return(for_clump)\n  }\n  datap_cause<-function(dat){\n    dat$p1<-pnorm(abs(dat$beta_hat_1/dat$seb1),lower.tail=F)*2\n    return(dat)\n  }\n  ld_local<-function(dat,r2,kb,p,LD_file){\n    library(plinkbinr)\n    \n    plink_pathway<-get_plink_exe()\n    \n    dat<-ld_clump(dat,clump_r2 = r2,clump_kb = kb,\n                  clump_p = p,\n                  plink_bin =plink_pathway , bfile =LD_file)\n    \n    return(dat)\n  }\n  if(\"list\"%in%class(outcome)){\n    single_expo=T\n    single_outcome=F}\n  if(\"list\"%in%class(expo)){\n    single_outcome=T\n    single_expo=F}\n  if(single_expo==T){\n    outcome<-pblapply(outcome,FUN=format_cause_out,cl=cl)\n    expo<-format_cause_expo(expo)\n  }\n  if(single_outcome==T){\n    expo<-pblapply(expo,FUN=format_cause_expo,cl=cl)\n    outcome<-format_cause_out(outcome)\n  }\n  \n  \n  if(single_outcome==T){dat<-pblapply(expo,outcome,FUN=gwas_merge,cl=cl)}\n  if(single_expo==T){dat<-pblapply(outcome,expo,\n                                   FUN=function(outcome,exposure)gwas_merge(exposure,outcome),\n                                   cl=cl)}\n  \n  \n  VAR<-pblapply(dat,1000000,FUN=sample_cause)\n  \n  est<-foreach(i=1:length(VAR)) %do%{\n    library(cause)\n    data<-est_cause_params(dat[[i]],VAR[[i]])\n  }\n  dat<-pblapply(dat,FUN=datap_cause)\n  for_clump<-lapply(dat, dat_clump_cause)\n  clumped<-pblapply(for_clump,0.001,10000,1e-05,LD_file,FUN=ld_local)\n  top_vars<-pblapply(clumped,FUN=function(dat) return(dat$rsid))\n  cause_res<-list()\n  for(i in 1:length(dat)){\n    library(cause)\n    res<-cause(dat[[i]],est[[i]],top_vars[[i]])\n    cause_res[[i]]<-res\n    print(i)\n  }\n  cause_table<-data.frame()\n  for (i in 1:length(cause_res)){\n    res<-cause_res[[i]]\n    elpd<-res$elpd\n    elpd$p<-pnorm(-elpd$z,lower.tail = F)\n    name<-paste0('file',i)\n    elpd$file<-name\n    cause_table<-rbind(cause_table,elpd)\n  }\n  return(cause_table)\n}\n\n# RAPS\nRAPS_getmr<-function(dat,dir_figure){\n  setwd(dir_figure)\n  res<-try(mr.raps(dat,over.dispersion = TRUE))\n  if(class(res)%in%\"try-error\"){}\n  else{\n    exposure<-dat$id.exposure\n    dir_create(exposure)\n    dir_in<-paste0(dir_figure,'/',exposure)\n    setwd(dir_in)\n    #plot_name<-paste0(exposure,'raps.pdf')\n    ggsave(file='raps_plot.pdf',plot=plot(res),width=9,height=5)\n    res<-data.frame(beta.raps=res$beta.hat,se.raps=res$beta.se,\n                    eov=res$tau2.hat,se.eov=res$tau2.se,OR.raps=NA,\n                    or_lci95.raps=NA,or_uci95.raps=NA)\n    res$OR.raps<- exp(res$beta.raps)\n    res$or_lci95.raps<-exp(res$beta.raps)-(res$beta.raps*1.96)\n    res$or_uci95.raps<-exp(res$beta.raps)+(res$beta.raps*1.96)\n    res$pval.raps<-2*pnorm(abs(res$beta.raps/res$se.raps),lower.tail=F) \n    res$pval.eov<-2*pnorm(abs(res$eov/res$se.eov),lower.tail=F)\n    if(is.na(res$pval.eov)==FALSE){\n      if(res$pval.eov >0.05 ){\n        res1<-mr.raps(dat,over.dispersion = F)\n        setwd(dir_in)\n        #plot_name<-paste0(exposure,'raps.pdf')\n        ggsave(file='raps_plot.pdf',plot=plot(res1),width=9,height=5)\n        res1<-data.frame(beta.raps=res1$beta.hat,se.raps=res1$beta.se,\n                         eov=NA,se.eov=NA)\n        res1$eov<-res$eov\n        res1$se.eov<-res$se.eov\n        res1$OR.raps<- exp(res1$beta.raps)\n        res1$or_lci95.raps<-exp(res1$beta.raps)-(res1$beta.raps*1.96)\n        res1$or_uci95.raps<-exp(res1$beta.raps)+(res1$beta.raps*1.96)\n        res1$pval.raps<-2*pnorm(abs(res1$beta.raps/res1$se.raps),lower.tail=F) \n        res1$pval.eov<-2*pnorm(abs(res1$eov/res1$se.eov),lower.tail=F)\n        \n        res<-res1\n      }\n    }\n    \n    return(res)\n  }\n}\n\nmr_dircreate_base<-function(root_dir,project_name,date=NULL){  \n  library(fs)\n  dir_name<-root_dir\n  setwd(dir_name)\n  \n  if(is.null(date)==FALSE){data_u<-date}else{data_u<-Sys.Date()}\n  \n  dir_name2<-project_name\n  dir_name3<-paste0(dir_name2,data_u)\n  dir_create(dir_name3)\n  setwd(paste0(dir_name,\"/\",dir_name3))\n  dir_name4<-\"1.figure\"\n  dir_name5<-\"2.table\"\n  dir_name6<-\"3.figure of sig res\"\n  dir_name7<-\"4.snp with Fval\"\n  \n  paste<-paste0(dir_name,\"/\",dir_name3,\"/\")\n  \n  dir1<-paste0(paste,dir_name4)\n  dir.create(dir1)\n  \n  dir2<-paste0(paste,dir_name5)\n  dir.create(dir2)\n  \n  dir3<-paste0(paste,dir_name6)\n  dir.create(dir3)\n  \n  dir4<-paste0(paste,dir_name7)\n  dir.create(dir4)\n  \n  res<-list(paste=paste,dir1=dir1,dir2=dir2,dir3=dir3,dir4=dir4)\n  \n  return(res)\n}\n\n\n\n# PRESSO\nmr_Presso<-function(dat,num=10000){\n  library(TwoSampleMR)\n  library(MRPRESSO)\n  library(dplyr)\n  set.seed(123)\n  try (mr_presso_res<-mr_presso(BetaOutcome =\"beta.outcome\", BetaExposure = \"beta.exposure\", SdOutcome =\"se.outcome\", SdExposure = \"se.exposure\", \n                                OUTLIERtest = TRUE,DISTORTIONtest = TRUE, data = dat,  \n                                SignifThreshold = 0.05,NbDistribution = num))\n  return(mr_presso_res)\n  \n}\nmr_presso_pval<-function(mr_presso_res){ \n  try ( mr_presso_main<-mr_presso_res$`Main MR results`)\n  try ( mr_presso_main[3:5,]<-NA) \n  return(mr_presso_main)\n}\n\n\nmr_presso_snp<-function(mr_presso_res,mr_presso_main,dat,type=\"list\"){\n  data_re<-list()\n  if(type==\"list\"){\n    for(i in 1:length(mr_presso_res)){\n      res<-mr_presso_res$`MR-PRESSO results`[[i]]\n      main<-mr_presso_main[[i]]\n      data<-dat[[i]]\n      try(if(is.na(main[2,6])==FALSE){\n        outliers<-which(res$`Outlier Test`$Pvalue<0.05)\n        data$mr_keep[outliers]<-FALSE\n      })\n      data_re[[i]]<-data\n      names(data_re)[[i]]<-names(dat)[[i]]\n    }\n    return(data_re)\n  }\n  \n  if(type==\"data\"){\n    res<-mr_presso_res$`MR-PRESSO results`\n    main<-mr_presso_main\n    data<-dat\n    try(if(is.na(main[2,6])==FALSE){\n      outliers<-which(res$`Outlier Test`$Pvalue<0.05)\n      data$mr_keep[outliers]<-FALSE\n    })\n    return(data)\n  }\n}\n\n#MRlap\n\nmr_lap<-function(expo,outcome,ld,hm3,pval,r2,kb,MR_reverse=1e-03,save_logfiles=F){\n  expo<-expo%>%select(rsid=SNP,chr=chr.exposure,pos=pos.exposure,alt=effect_allele.exposure,\n                      ref=other_allele.exposure,N=samplesize.exposure,beta=beta.exposure,\n                      se=se.exposure)\n  expo<-as.data.frame(expo)\n  outcome<-outcome%>%select(rsid=SNP,chr=chr.outcome,pos=pos.outcome,alt=effect_allele.outcome,\n                            ref=other_allele.outcome,N=samplesize.outcome,beta=beta.outcome,\n                            se=se.outcome)\n  outcome<-as.data.frame(outcome)\n  n_expo<-expo$exposure[1]\n  n_out<-outcome$outcome[1]\n  \n  try(res<-MRlap::MRlap(exposure = expo,\n                        exposure_name = n_expo,\n                        outcome = outcome,\n                        outcome_name = n_out,\n                        ld = ld,\n                        hm3 = hm3,MR_threshold=pval,MR_pruning_dist=kb,\n                        MR_pruning_LD=r2,MR_reverse=MR_reverse,save_logfiles=save_logfiles\n  ))\n  try(snp<-data.frame(SNP_MRlap=res$MRcorrection$IVs))\n  try(res_c<-as.data.frame(res$MRcorrection[-4])%>%select(nsnp=m_IVs,\n                                                          beta_MRlap=corrected_effect,\n                                                          se_MRlap=corrected_effect_se,\n                                                          p_MRlap=corrected_effect_p))\n  try(res<-c(res,res_c,snp))\n  \n  try(return(res))\n}\n\n\n# clean\nclean_expo<-function(expo,pval,low_af=0.5,high_af=0.5,\n                     clump=TRUE,kb=10000,r2=0.001,LD_file=NULL,af_filter=FALSE){\n  library(TwoSampleMR)\n  dat<-subset(expo,pval.exposure<pval)\n  if(af_filter==TRUE){dat<-subset(dat,eaf.exposure<low_af|eaf.exposure>high_af)}\n  \n  if(clump==TRUE){\n    \n    if(is.null(LD_file)==TRUE){\n      dat<-clump_data(dat,clump_kb = kb,clump_r2 = r2)}\n    else{\n      library(plinkbinr)\n      plink_pathway<-get_plink_exe()\n      snp<-data.frame(rsid=dat$SNP,pval=dat$pval.exposure)\n      snp<-try(ld_clump(snp,clump_kb = kb,clump_r2 = r2,plink_bin =plink_pathway , bfile =LD_file))\n      if (\"try-error\"%in% class(snp)){return(dat)}\n      else{\n        snp<-data.frame(SNP=snp$rsid)\n        dat<-merge(snp,dat,by.x=\"SNP\",by.y='SNP')\n      }\n    }\n    \n  }\n  return(dat)\n}\n\nclean_list<-function(list,nrow=10){\n  l<-lapply(list,nrow)\n  n<-data.frame()\n  for(i in 1:length(l)){\n    if(is.null(l[[i]])==T || l[[i]]==0 )next\n    \n    n1<-data.frame(i,l[[i]])\n    n<-rbind(n,n1)\n  }\n  colnames(n)<-c('l','row')\n  n<-subset(n,row>nrow)\n  list<-list[n$l]\n  return(list)\n}\n\nclean_IV_from_outsig<-function(dat,MR_reverse=1e-03){\n  dat<-subset(dat,pval.outcome>MR_reverse)\n  return(dat)\n}\n\n\nLDSC_rg<-function(expo,outcome,an,sample_prev=NA,\n                  population_prev=NA,ld,wld,chr_filter=c(1:22),n_blocks=200){\n  id.o<-outcome$id.outcome[1]\n  id.e<-expo$id.exposure[1]\n  \n  expo<-expo%>%mutate(Z=beta.exposure/se.exposure)\n  expo<-expo%>%select(SNP=SNP,N=samplesize.exposure,Z=Z\n                      ,A1=effect_allele.exposure\n                      ,A2=other_allele.exposure)\n  expo<-as_tibble(expo)\n  \n  outcome<-outcome%>%mutate(Z=beta.outcome/se.outcome)\n  outcome<-outcome%>%select(SNP=SNP,N=samplesize.outcome,Z=Z\n                            ,A1=effect_allele.outcome\n                            ,A2=other_allele.outcome)\n  outcome<-as_tibble(outcome)\n  \n  \n  dat<-list(expo,outcome)\n  names(dat)<-c(id.e,id.o)\n  \n  rm(expo,outcome)\n  \n  \n  res<-try(ldscr::ldsc_rg(dat,ancestry = an,sample_prev=sample_prev,\n                          population_prev=population_prev,ld=ld,wld=wld,\n                          n_blocks=n_blocks,chr_filter=chr_filter))\n  \n  return(res)\n  \n}\n\n"], ["/Get_MR/1.0/Get_MR1.0dependence.R", "## 保证你的R版本是4.2及以上!!\ninstall.packages(\"devtools\")\nif (!require(\"BiocManager\", quietly = TRUE))\n  install.packages(\"BiocManager\")\ndevtools::install_github(\"rondolab/MR-PRESSO\")\ndevtools::install_github(\"MRCIEU/TwoSampleMR\")\ndevtools::install_github(\"explodecomputer/plinkbinr\")\ndevtools::install_github(\"mrcieu/ieugwasr\")\ndevtools::install_github(\"jean997/cause\")\nBiocManager::install(\"MungeSumstats\")\ndevtools::install_github(\"n-mounier/MRlap\")\ndevtools::install_github(\"mglev1n/ldscr\")\ninstall.packages(c('dplyr','tidyr','data.table','stringr','vroom','mr.raps','pbapply','doParallel'))\n"], ["/Get_MR/1.0/Install_Reference_Genome.r", "BiocManager::install(\"SNPlocs.Hsapiens.dbSNP155.GRCh37\")\nBiocManager::install(\"BSgenome.Hsapiens.1000genomes.hs37d5\")\nBiocManager::install(\"SNPlocs.Hsapiens.dbSNP155.GRCh38\")\nBiocManager::install(\"BSgenome.Hsapiens.NCBI.GRCh38\")\n"]], "task_instance_info": {"created_time": "2025-08-21 00:59:47", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(base_res,presso_pval,egger_res,test_res) {}", "code_description": "This code segment functions to: Consolidate results from multiple statistical methods by iteratively merging output columns based on shared identifiers, aligning analysis components from different hypothesis testing frameworks into a unified data structure through row-wise combination of matched records."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nbind_pressomr <- function(base_res, presso_pval, egger_res, test_res) {\n  res_all <- cbind(base_res, presso_pval, egger_res, test_res)\n  return(res_all)\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-00-22"}, "editdistance_info": {"edit_distance": 11.4068, "calculate_time": "2025-08-21 01:00:22", "true_code_clean": "function(base_res,presso_pval,egger_res,test_res){\n  presso_id<-names(presso_pval)\n  presso_pval<-bind_rows(presso_pval)\n  base_res<-bind_rows(base_res)\n  egger_res<-bind_rows(egger_res)\n  test_res<-bind_rows(test_res)\n  res_all<-data.frame()\n  for(i in 1:nrow(base_res)){\n    if(i%%5==1){\n      id<-base_res$id.exposure[i]\n      num.bg<-5*(which(presso_id==id)[1]-1)+1\n      num.end<-num.bg+4\n      res<-cbind(base_res[i:(i+4),],presso_pval[num.bg:num.end,2:6])\n      num.bg<-which(egger_res$id.exposure==id)\n      num.end<-num.bg+4\n      res<-cbind(res,egger_res[num.bg:num.end,3:5])\n      num.bg<-which(test_res$id.exposure==id)[1]\n      num.end<-num.bg+4\n      res<-cbind(res,test_res[num.bg:num.end,3:6])\n      res_all<-rbind(res_all,res)\n    }\n  }\n  return(res_all)\n}", "predict_code_clean": "bind_pressomr <- function(base_res, presso_pval, egger_res, test_res) {\n  res_all <- cbind(base_res, presso_pval, egger_res, test_res)\n  return(res_all)\n}"}}