1) This is not exactly what you are asking for but maybe it will help anyways:
library(Ryacas)
x <- Sym("x")
y <- Sym("y")
Simplify(Solve(List(x - y == 0, x + 2*y == 3), List(x, y)))
giving:
expression(list(list(x - y == 0, y - 1 == 0)))
2) If we know these are linear equations exactly of the form shown in the question then try this. The two strapply
calls perform matches of the regular expression against the components of args
, capture the strings matched by the portions of the regular expressions within parentheses and call the function specified as the third argument with those captured strings as arguments. We combine the strapply
outputs using rbind.fill
and replace any NAs it generates with zero.
library(gsubfn) # strapply
library(plyr) # rbind.fill
eqn <- function(...) {
args <- c(...)
x2num <- function(x, y) { # determine coefficient value as a numeric
z <- gsub(" ", "", x)
setNames(if (z == "-") -1 else if (z == "") 1 else as.numeric(z), y)
}
lhs <- strapply(args, "(-? *\\d*)[ *]*([a-z])", x2num)
lhs <- do.call(rbind.fill, lapply(lhs, function(x) as.data.frame(t(x))))
lhs <- as.matrix(lhs)
lhs[] <- ifelse(is.na(lhs), 0, lhs)
list(lhs = lhs, rhs = strapply(args, "== *(\\d)", as.numeric, simplify = TRUE))
}
# test it out
eqn("x - y == 0", "2*y == 3")
giving:
$lhs
x y
[1,] 1 -1
[2,] 0 2
$rhs
[1] 0 3
Update: Generalized so that now not all variables need to be in each equation and also variables can be in different orders in different equations.