gpt4 book ai didi

在 Excel 中运行 R 脚本

转载 作者:行者123 更新时间:2023-12-02 19:07:00 24 4
gpt4 key购买 nike

关于如何执行此操作的信息并不多。我尝试在网上研究一个博客,并在VBA中实现了以下代码(带有R文件的路径):-

Sub RunRscript()
'runs an external R code through Shell
'The location of the RScript is 'C:\R_code'
'The script name is 'hello.R'

Dim shell As Object
Set shell = VBA.CreateObject("WScript.Shell")
Dim waitTillComplete As Boolean: waitTillComplete = True
Dim style As Integer: style = 1
Dim errorCode As Integer
Dim path As String
path = "RScript C:\R_code\hello.R"
errorCode = shell.Run(path, style, waitTillComplete)
End Sub

Source

但是,当我在 Excel 中运行宏时,它基本上什么也不做 - 只是在 RStudio 中打开脚本。我没有收到任何错误,但它没有给出任何输出 - 只是在 Rstudio 中打开 R 脚本。我做错了什么?

另外,如果我需要在 Excel 中使用 R,这种方法是否有效,或者基本上我需要安装软件 RExcel?

任何其他在 Excel 中使用 R 的链接/信息将不胜感激。谢谢:)

最佳答案

它在 RStudio 中打开似乎很奇怪。我建议直接通过 R.exe 运行它。根据您告诉我们的内容,路径似乎设置正确。因此,如果不需要输出,您可以像这样调用 R.exe:

Sub RunRscript()
Shell ("R CMD BATCH C:\R_code\hello.R")
End Sub

如果您需要输出,那么您需要创建一个如下所示的 WshShell 对象:

Sub RunRscript()
Dim output As String
output = CreateObject("WScript.Shell").Exec("R CMD BATCH C:\R_code\hello.R").StdOut.ReadAll
End Sub

这是运行 R 脚本的较旧方法,但目前应该可以正常工作。您可能需要进一步检查 R 的安装,看看是否存在任何其他问题。

关于在 Excel 中运行 R 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49449934/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com