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
組件匹配,捕獲括號內正則表達式部分匹配的字符串,並將那些捕獲的字符串作爲參數調用指定爲第三個參數的函數。我們將strapply
輸出結合使用rbind.fill
,並將其生成的所有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")
,並提供:
$lhs
x y
[1,] 1 -1
[2,] 0 2
$rhs
[1] 0 3
更新:廣義所以現在不是所有的變量需要在每個方程中,也變量可以在不同的公式不同的訂單。
你會用這個做什麼?只需直接輸入矩陣即可輕鬆打字。 – Roland 2014-11-22 12:10:59