我正在尝试通过R软件解决线性编程问题。我有三个名为A.txt,B.txt,F.txt的文件。我已通过以下代码阅读此内容:
library( linprog )
Amat<-read.table("D:/Simplex/SimplexInitialTheoryWithRsoftware/src/A.txt",header=FALSE,sep=" ")
bvec<-read.table("D:/Simplex/SimplexInitialTheoryWithRsoftware/src/B.txt",header=FALSE,sep=" ")
cvec<-read.table("D:/Simplex/SimplexInitialTheoryWithRsoftware/src/F.txt",header=FALSE,sep=" ")
该文件的链接是A.txt,B.txt,F.txt。我试图通过以下代码通过R软件解决这个问题。
res <- solveLP( cvec, bvec, Amat, TRUE )
## print the results
print( res )
但是我收到以下错误。
Error in solveLP(cvec, bvec, Amat, TRUE) :
Matrix A must have as many rows as constraints (=elements of vector b) and as many columns as variables (=elements of vector c).
但我一次又一次检查了我的档案。 A的尺寸为10×10,B的尺寸为10×1,F的尺寸为1×10。
为什么我收到错误?
更新: 我在以下代码后遇到错误。
cvec<-read.table("D:/Simplex/SimplexInitialTheoryWithRsoftware/src/F.txt",header=FALSE,sep=" ")
错误是
Warning message:
In read.table("D:/Simplex/SimplexInitialTheoryWithRsoftware/src/F.txt", :
incomplete final line found by readTableHeader on 'D:/Simplex/SimplexInitialTheoryWithRsoftware/src/F.txt'
我的假设是,错误是由于这行代码引起的。
答案 0 :(得分:3)
根据Roland的评论,错误来自输入对象的错误指定。以下代码经过试用和测试:
library( linprog )
Amat<-as.matrix(read.table("C:\\Users\\ifragkos\\Documents\\Fun\\R\\A.txt",header=FALSE,sep=" "))
bvec<-c(read.table("C:\\Users\\ifragkos\\Documents\\Fun\\R\\B.txt",header=FALSE,sep=" "), recursive=T)
cvec<-c(read.table("C:\\Users\\ifragkos\\Documents\\Fun\\R\\F.txt",header=FALSE,sep=" "), recursive=T)
res<-solveLP(cvec, bvec, Amat, TRUE)
## print the results
print( res )
结果:
All Variables (including slack variables)
opt cvec min.c max.c marg marg.reg
V1 0.2374153 29.02 21.255258 73.654167 NA NA
V2 0.0000000 47.98 -Inf 79.114957 -31.13496 0.0672461
V3 0.0000000 -37.64 -Inf 53.342215 -90.98222 0.0751398
V4 0.0000000 -22.01 -Inf 95.534330 -117.54433 0.0529444
V5 0.0000000 -1.36 -Inf 45.246038 -46.60604 0.1159432
V6 0.0000000 4.72 -Inf 55.904385 -51.18439 0.0139935
V7 0.0000000 19.67 -Inf 122.901935 -103.23194 0.0450489
V8 0.0000000 24.32 -Inf 93.315656 -68.99566 0.0420672
V9 0.0000000 46.15 -Inf 57.745346 -11.59535 0.0444139
V10 0.0132743 48.21 18.994909 87.790333 NA NA
S V11 20.1358135 0.00 -0.497478 0.546882 0.00000 NA
S V12 24.2133223 0.00 -10.046381 0.432213 0.00000 NA
S V13 44.8115881 0.00 NA 0.155625 0.00000 NA
S V14 75.7667354 0.00 -1.509427 0.454518 0.00000 NA
S V15 1.3688361 0.00 -0.826885 0.312089 0.00000 NA
S V16 66.5207843 0.00 NA 0.123910 0.00000 NA
S V17 47.0617343 0.00 NA 0.181379 0.00000 NA
S V18 0.0000000 0.00 -Inf 0.456100 -0.45610 0.8502727
S V19 0.0000000 0.00 -Inf 1.084168 -1.08417 2.8651162
S V110 72.7149517 0.00 -0.919381 0.124553 0.00000 NA
免责声明:这是我在R
的第一篇文章,我绝不是R
专家。根据{{1}}和@Roland的评论,我对as.vector
进行了一些调整,查看了linprog reference和this SO post的示例并且来了提出上述建议。
The reference of the c() function解释了linprog API
&#34;递归地下降通过列表(和pairlists)将所有元素组合成一个向量。&#34;省略递归导致默认recursive = TRUE
,这导致整个数据帧仅作为一个元素返回:
recursive = FALSE
我希望这有帮助!