ourMELONS/R/matlab2r.R

50 lines
1.6 KiB
R
Raw Normal View History

2020-11-09 14:30:09 +01:00
#' @title Convert Matlab function to R
2020-11-09 15:00:07 +01:00
#' @description Performs basic syntax conversion from Matlab to R
2020-11-09 14:30:09 +01:00
#' @param filename name of the file
#' @param saveOutput if `TRUE`, `filename` is overwritten. Defaults to `FALSE`
2020-11-09 15:00:07 +01:00
#' @return text converted to R, printed to screen or replacing input file
2020-11-09 14:30:09 +01:00
#' @author Waldir Leoncio
#' @export
matlab2r <- function(filename, saveOutput = FALSE) {
# Verification
if (!file.exists(filename)) stop("File not found")
# Reading file into R
txt <- readLines(filename)
# Replacing text
2020-11-09 15:00:07 +01:00
txt <- gsub(
2020-11-09 15:22:56 +01:00
pattern = "function (.+)\\s+=\\s*(.+)\\((.+)\\)",
2020-11-09 15:00:07 +01:00
replacement = "\\2 <- function(\\3) { return(\\1)",
x = txt
)
2020-11-09 15:22:56 +01:00
# txt <- gsub("\\%\\s*(\\w+)", "# \\1", txt)
2020-11-09 14:30:09 +01:00
txt <- gsub(";", "", txt)
txt <- gsub("for (.+)=(.+)", "for (\\1 in \\2) {", txt)
txt <- gsub("end", "}", txt)
2020-11-09 15:22:56 +01:00
txt <- gsub("(.),(\\S)", "\\1, \\2", txt)
2020-11-09 15:00:07 +01:00
# TODO: replace forms like (:,:) with [, ]
2020-11-09 15:22:56 +01:00
# TODO: add argument to skip some of these rules
txt <- gsub("if (.+)", "if (\\1) {", txt) # FIXME: paste comments after {
txt <- gsub("else$", "} else {", txt)
txt <- gsub("elseif", "} else if", txt)
txt <- gsub("\\(~", "(!", txt)
txt <- gsub("while (.+)", "while \\1 {", txt)
## Math operators
txt <- gsub("(\\S)\\+(\\S)", "\\1 + \\2", txt)
txt <- gsub("(\\S)\\-(\\S)", "\\1 - \\2", txt)
txt <- gsub("(\\S)\\*(\\S)", "\\1 * \\2", txt)
2020-11-09 14:30:09 +01:00
# Returning converted code
if (!saveOutput) {
return(cat(txt, sep="\n"))
} else {
return(
write.table(
x = txt,
file = filename,
quote = FALSE,
row.names = FALSE,
col.names = FALSE
)
)
}
2020-11-09 15:00:07 +01:00
}