R/rmd_convert.R

# rmd_convert

rmd_convert <- function(infile, keep.txt=TRUE){
  file <- readLines(infile)
  code_start <- which(grepl(file, pattern = '```{r*', perl = TRUE))

  code_end <- sapply(code_start, function(x){
    preidx <- which(grepl(file[-(1:x)], pattern = '```', perl = TRUE))[1]
    return(preidx + x)
  })

  fun1 <- function(start, end){
    start <- start + 1
    end <- end - 1
    return(start:end)
  }

  idx <- unlist(mapply(FUN = fun1,
                       start = code_start,
                       end = code_end,
                       SIMPLIFY = FALSE)
  )

  com_idx <- 1:length(file)
  un_com_idx <- com_idx[-idx]

  if(keep.txt==TRUE){
    file[un_com_idx] <- paste('## ', file[un_com_idx], sep = '')
  } else {
    file[un_com_idx] <- ''
  }

  name <- strsplit(infile, split = '\\.')[[1]][1]
  file_out <- file(paste(name, '.R', sep = ''), 'w')

  for(x in com_idx){
    cat(file[x], '\n', file = file_out)
  }

  close(file_out)

}
sndean/RmdTo documentation built on May 17, 2019, 8:45 p.m.