函数将线性方程转换为R?中的矩阵形式?

函数将线性方程转换为R?中的矩阵形式?,r,matrix,equation-solving,linear-equation,R,Matrix,Equation Solving,Linear Equation,我想知道是否存在能够将线性方程组转换为矩阵形式的R的包或其他预构建解决方案(例如,对于通过的解决方案),类似于等式矩阵(eqns,vars) Matlab中的一个示例: [A, b] = equationsToMatrix([x - y == 0, x + 2*y == 3, [x, y]) A = [ 1, -1] [ 1, 2] b = 0 3 关于构建块的建议也会非常有用。1)这并不是你想要的,但可能会有所帮助: library(Ryacas) x <- Sym("x"

我想知道是否存在能够将线性方程组转换为矩阵形式的R的包或其他预构建解决方案(例如,对于通过的解决方案),类似于
等式矩阵(eqns,vars)

Matlab中的一个示例:

[A, b] = equationsToMatrix([x - y == 0, x + 2*y == 3, [x, y])

A =
[ 1, -1]
[ 1, 2]

b =
  0
  3
关于构建块的建议也会非常有用。

1)这并不是你想要的,但可能会有所帮助:

library(Ryacas)
x <- Sym("x")
y <- Sym("y")
Simplify(Solve(List(x - y == 0, x + 2*y == 3), List(x, y)))
2)如果我们知道这些都是与问题中所示形式完全相同的线性方程,那么试试这个。两个
stripply
调用将正则表达式与
args
的组件进行匹配,捕获与括号内正则表达式部分匹配的字符串,并调用指定为第三个参数的函数,将捕获的字符串作为参数。我们使用
rbind.fill
组合
stripply
输出,并将其生成的任何NAs替换为零

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")

更新:通用化,因此现在并非所有变量都需要在每个方程中,变量也可以在不同的方程中处于不同的顺序。

无法从您的示例中判断您只需要简单的线性方程解算器还是更通用的系统解算器。如果是后者,请查看
BB
nleqslv


您可能还对某个严重扭曲的头脑编写的“包装器”工具感兴趣:-),它位于package
ktsolve
中。最后一个工具允许您设置任意一组方程,并对任何所需的变量集进行反解。

您将使用它做什么?直接输入矩阵就不用打字了。我不知道这个存在。太棒了!谢谢!这是非常接近我要找的,谢谢!
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