You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R中lpSolve包使用及安装报错问题求助

问题:安装lpSolve包失败导致R代码无法运行

尝试运行一段计算总变差距离的R代码:

library(lpSolve)
f.obj <- c(0, 1, 1, 1, 0, 1, 1, 1, 0)

f.con <- matrix (c(1, 0, 0, 1, 0, 0, 1, 0, 0,
                   0, 1, 0, 0, 1, 0, 0, 1, 0,
                   0, 0, 1, 0, 0, 1, 0, 0, 1,
                   1, 1, 1, 0, 0, 0, 0, 0, 0,
                   0, 0, 0, 1, 1, 1, 0, 0, 0,
                   0, 0, 0, 0, 0, 0, 1, 1, 1 
), nrow=6, byrow=TRUE)
f.dir <- c("=", "=", "=", "=", "=", "=")
f.rhs <- c(1/2, 1/3, 1/6, 1/3, 1/6,1/2)
# Now run.
lpSoln <- lp ("min", f.obj, f.con, f.dir, f.rhs)

执行后出现错误:

> lpSoln
Error: object 'lpSoln' not found

怀疑是lpSolve包未安装,执行install.packages("lpSolve")时又出现编译失败的报错:

> install.packages("lpSolve")
Installing package into ‘/usr/local/lib/R/4.1/site-library’
(as ‘lib’ is unspecified)
trying URL 'https://cran.rstudio.com/src/contrib/lpSolve_5.6.19.tar.gz'
Content type 'application/x-gzip' length 468223 bytes (457 KB)
==================================================
downloaded 457 KB

* installing *source* package ‘lpSolve’ ...
** package ‘lpSolve’ successfully unpacked and MD5 sums checked
** using staged installation
** libs
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun
ERROR: compilation failed for package ‘lpSolve’
* removing ‘/usr/local/lib/R/4.1/site-library/lpSolve’
Warning in install.packages :
  installation of package ‘lpSolve’ had non-zero exit status

The downloaded source packages are in
    ‘/private/var/folders/sk/m5rzd54n6_q492pn1rn_dzbh0000gn/T/Rtmp6GpqFy/downloaded_packages’

附sessionInfo信息:

> sessionInfo()
R version 4.1.2 (2021-11-01)
Platform: x86_64-apple-darwin20.6.0 (64-bit)
Running under: macOS Monterey 12.6

Matrix products: default
LAPACK: /usr/local/Cellar/r/4.1.2/lib/R/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] compiler_4.1.2 tools_4.1.2   
> 

解决建议

1. 修复macOS缺失的Command Line Tools

报错核心是xcrun: error: invalid active developer path,说明系统缺少编译所需的开发者工具链:

  • 打开终端,运行命令:xcode-select --install
  • 按照弹出的提示完成Command Line Tools的安装
  • 如果安装后仍有问题,尝试重置开发者路径:sudo xcode-select --reset

2. 重新安装lpSolve包

完成工具安装后,重启R/RStudio,执行以下命令重新安装:

install.packages("lpSolve")

3. 验证安装并运行代码

安装成功后,先加载包确认无报错:

library(lpSolve)

再运行原来的计算总变差距离的代码,此时lpSoln对象应该能正常生成,不会再出现未找到的错误。


内容的提问来源于stack exchange,提问作者Ommo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 23:34:57