1)这并不完全是您所要求的,但也许无论如何都会有帮助:
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)如果我们知道这些线性方程与问题中所示的形式完全相同,那么请尝试这个。他们俩strapply
调用执行正则表达式与以下组件的匹配args
,捕获与括号内的正则表达式部分匹配的字符串,并使用捕获的字符串作为参数调用指定为第三个参数的函数。我们结合strapply
输出使用rbind.fill
并将其生成的任何 NA 替换为零。
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:广义而言,现在并非所有变量都需要位于每个方程中,并且变量在不同方程中可以具有不同的顺序。