C# 从C运行R脚本
我有下面的R脚本和C程序,用作从C调用R的示例。如果我从R-GUI中运行脚本,我会看到预期的输出。然而,如果我在C中运行它,如下所示,我不会得到任何输出。我尝试将R脚本移动到C可执行目录中,但这也不起作用。我尝试以管理员身份运行Visual Studio,但仍然没有输出 不确定我做错了什么: R代码:C# 从C运行R脚本,c#,r,C#,R,我有下面的R脚本和C程序,用作从C调用R的示例。如果我从R-GUI中运行脚本,我会看到预期的输出。然而,如果我在C中运行它,如下所示,我不会得到任何输出。我尝试将R脚本移动到C可执行目录中,但这也不起作用。我尝试以管理员身份运行Visual Studio,但仍然没有输出 不确定我做错了什么: R代码: # Gradient Boosting model with gbm # Turn off library warning messages suppressWarnings(library(gb
# Gradient Boosting model with gbm
# Turn off library warning messages
suppressWarnings(library(gbm))
# gbm result for simulated data
get_gbm <- function()
{
set.seed(123)
a <- sample(1:10, 250, replace = T)
b <- sample(10:20, 250, replace = T)
flag <- ifelse(a > 5 & b > 10, "red", ifelse(a < 3, "yellow", "green"))
df <- data.frame(a = a, b = b, flag = as.factor(flag))
train <- df[1:200,]
test <- df[200:250,]
mod_gb <- gbm(flag ~ a + b,
data = train,
distribution = "multinomial",
shrinkage = .01,
n.minobsinnode = 10,
n.trees = 100)
pred <- predict.gbm(object = mod_gb,
newdata = test,
n.trees = 100,
type = "response")
res <- cbind(test, pred)
return(res)
}
# need to call function to get the output
get_gbm()
如何从R调用脚本,是否运行源代码?您的脚本似乎没有显式打印任何内容,因此,当以非交互方式运行代码时,我认为不会打印任何内容。如果希望将结果打印到控制台,请尝试将最后一行更改为printget_gbm。不确定您在问什么re:source-我在上面的代码中给出了从C调用R脚本的确切方式。添加printgbm没有任何作用。您说过,如果我从R-GUI中运行脚本。不清楚你说的到底是什么意思。你是否复制/粘贴到控制台或其他地方了。还是运行了sourceScript.R?后者更接近于运行Rscript时发生的情况。在R-GUI中,我打开脚本,选择所有文本,然后点击run按钮。工作完美。这段代码调用Rscript.exe,它可能是同一个程序,只是没有GUI,只是一个控制台。可能出错的一件事是,我在GUI中安装了gbm包,但不知道Rscript是否也看到了该包?我在这里发现了几乎完全相同的问题:
using System;
using System.Diagnostics;
using System.IO;
class Program
{
static void Main(string[] args)
{
var rmainpath = @"C:\Program Files\R\R-4.0.3";
var rpath = rmainpath + @"\bin\Rscript.exe";
var mainGoogleDrivePath = @"C:\Users\Administrator\Google Drive";
//var scriptpath = mainGoogleDrivePath + @"\repos\rsource\Script.R";
var scriptpath = mainGoogleDrivePath + @"\Projects\RFromCSharp\RFromCSharp\bin\Debug\Script.R";
var output = RunRScript(rpath, scriptpath);
Console.WriteLine(output); // output is empty
Console.ReadLine();
}
private static string RunRScript(string rpath, string scriptpath)
{
try
{
var info = new ProcessStartInfo
{
FileName = rpath,
WorkingDirectory = Path.GetDirectoryName(scriptpath),
Arguments = scriptpath,
RedirectStandardOutput = true,
CreateNoWindow = true,
UseShellExecute = false
};
using (var proc = new Process { StartInfo = info })
{
if (false == proc.Start())
throw new Exception("Didn't start R");
return proc.StandardOutput.ReadToEnd();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return string.Empty;
}
}