Run R script in Excel

丶灬走出姿态 提交于 2019-11-28 05:58:31

问题


There isn't a lot of information on how to do this. I tried to study a blog online and implemented the following code in VBA(with the path of the R file):-

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

However, when I run the macro in Excel, it basically does nothing-just opens the script in RStudio. I am not getting any error, but it's not giving any output-just opens the R script in Rstudio. What am I doing wrong?

Also, does this method work or basically I need to install the software RExcel, if I need to use R in Excel?

Any other link/information to use R in Excel would be appreciated. Thanks:)


回答1:


It seems quite odd that it is opening in RStudio. I would suggest running it straight through R.exe. It looks like the PATH is setup all correctly from what you have told us. So you can call R.exe like this if don't need the output:

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

If you need the output then you'll need to make a WshShell object like this:

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

This is the older way to run R scripts but should work fine for the time being. You may want to look into your installation of R a bit more to see if there are any other problems.



来源:https://stackoverflow.com/questions/49449934/run-r-script-in-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!