1) 这并不完全符合您的要求,但无论如何它可能会有所帮助:
library(Ryacas)
x <- Sym("x")
y <- Sym("y")
Simplify(Solve(List(x - y == 0, x + 2*y == 3), List(x, y)))
给予:
expression(list(list(x - y == 0, y - 1 == 0)))
2) 如果我们知道这些是问题中所示形式的线性方程,那么试试这个。两个strapply 调用执行正则表达式与args 的组件的匹配,捕获括号内正则表达式部分匹配的字符串,并以这些捕获的字符串作为参数调用指定为第三个参数的函数。我们使用rbind.fill 组合strapply 输出并将其生成的任何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")
给予:
$lhs
x y
[1,] 1 -1
[2,] 0 2
$rhs
[1] 0 3
更新: 广义化,因此现在并非所有变量都需要在每个方程中,而且变量可以在不同方程中以不同的顺序排列。