我正在尝试从Java构建R的data.frame。当填充int / double值时,它将转换为R中的data.frame,但是当我尝试使用标签数据时,它将抛出未找到对象的异常。
public static void main(String[] args) throws ScriptException, FileNotFoundException {
RenjinScriptEngineFactory factory = new RenjinScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine();
engine.eval("source(\"script.R\")");
engine.eval("workflow.predict("+getData()+")");
}
public static ListVector getData() {
StringArrayVector.Builder userid = new StringArrayVector.Builder();
StringArrayVector.Builder defaultCC = new StringArrayVector.Builder();
StringArrayVector.Builder expenseTypeId = new StringArrayVector.Builder();
StringArrayVector.Builder amount = new StringArrayVector.Builder();
StringArrayVector.Builder cc = new StringArrayVector.Builder();
StringArrayVector.Builder activity = new StringArrayVector.Builder();
userid.add("62020");
defaultCC.add("3141877");
expenseTypeId.add("46013");
amount.add("1000");
cc.add("3141877");
activity.add("72004");
userid.add("62020");
defaultCC.add("3141877");
expenseTypeId.add("46013");
amount.add("1001");
cc.add("3141877");
activity.add("72001");
ListVector.NamedBuilder myDf = new ListVector.NamedBuilder();
myDf.setAttribute(Symbols.CLASS, StringVector.valueOf("data.frame"));
myDf.setAttribute(Symbols.ROW_NAMES, new RowNamesVector(2));
myDf.add("userid", userid.build());
myDf.add("defaultCC", defaultCC.build());
myDf.add("expenseTypeId", expenseTypeId.build());
myDf.add("amount", amount.build());
myDf.add("cc", cc.build());
myDf.add("activity", activity.build());
return myDf.build();
}
script.R
workflow.predict <- function(abc) {
print(data.frame(lapply(abc, as.character), stringsAsFactors=FALSE))
dataset = data.frame(lapply(abc, as.character), stringsAsFactors=FALSE)
library(randomForest)
classifier = randomForest(x = dataset[-6], y = as.factor(dataset$activity))
# Predicting the Test set results
new.data=c(62020,3141877,46013,950,3141877)
y_pred = predict(classifier, newdata = new.data)
print(y_pred)
return(y_pred)
}
但是当我尝试使用标签数据时,它会抛出错误以下消息。
Code
userid.add("a");
Exception in thread "main" org.renjin.eval.EvalException: object 'a' not found
at org.renjin.eval.Context.evaluateSymbol(Context.java:335)
at org.renjin.eval.Context.evaluate(Context.java:278)
at org.renjin.eval.Context.evaluate(Context.java:264)