dre*_*mon 5 linear-equation r matrix equation-solving
我想知道R是否存在能够将线性方程组转换成矩阵形式的任何包或其他预构建解决方案(例如,通过Gauss Seidel算法求解),类似于equationsToMatrix(eqns,vars) Matlab中的函数?
Matlab的一个例子:
[A, b] = equationsToMatrix([x - y == 0, x + 2*y == 3, [x, y])
A =
[ 1, -1]
[ 1, 2]
b =
0
3
Run Code Online (Sandbox Code Playgroud)
关于构建块的建议也非常有用.
1)这并不完全是您所要求的,但也许无论如何都会有帮助:
library(Ryacas)
x <- Sym("x")
y <- Sym("y")
Simplify(Solve(List(x - y == 0, x + 2*y == 3), List(x, y)))
Run Code Online (Sandbox Code Playgroud)
给予:
expression(list(list(x - y == 0, y - 1 == 0)))
Run Code Online (Sandbox Code Playgroud)
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")
Run Code Online (Sandbox Code Playgroud)
给予:
$lhs
x y
[1,] 1 -1
[2,] 0 2
$rhs
[1] 0 3
Run Code Online (Sandbox Code Playgroud)
更新:广义化,现在并非所有变量都需要位于每个方程中,并且变量在不同方程中可以具有不同的顺序。