使用Renjin在Java与R间互传DataFrame遇externalptr问题求助
Hey there, I see exactly what's causing that frustrating externalptr problem when passing your DataFrame between Java and Renjin! Let's break this down and fix it quickly.
The Root Cause
Looking at your code, you're passing the ListVector.NamedBuilder object directly to the Renjin engine with engine.put("df", dfProcessos); — but Renjin doesn't know how to handle the builder itself. It treats this unbuilt, intermediate object as an external pointer instead of recognizing it as a proper R data.frame.
The Fix
You just need to call the build() method on your dfProcessos builder to create the actual ListVector (which Renjin interprets as an R data.frame) before passing it to the engine.
Here's the corrected section of your code, with the key change highlighted:
// ... your existing code ... ListVector.NamedBuilder dfProcessos = new ListVector.NamedBuilder(); dfProcessos.setAttribute(Symbols.CLASS, StringVector.valueOf("data.frame")); dfProcessos.setAttribute(Symbols.ROW_NAMES, new RowNamesVector(processosJulgados.size())); dfProcessos.add("processos", numProcParaR.build()); RenjinScriptEngineFactory factory = new RenjinScriptEngineFactory(); ScriptEngine engine = factory.getScriptEngine(); // FIX: Pass the built ListVector instead of the builder engine.put("df", dfProcessos.build()); // <-- This line was updated try { engine.eval("str(df)"); } catch (ScriptException ex) { Logger.getLogger(TesteRenjin.class.getName()).log(Level.SEVERE, null, ex); } // ... rest of your code ...
Bonus: Retrieving DataFrames from R back to Java
If you later need to pull the modified data.frame from Renjin back to Java (and avoid another externalptr issue), cast the retrieved object directly to ListVector:
// After running R code that modifies the df object ListVector retrievedDf = (ListVector) engine.get("df"); // Access specific columns like this: StringArrayVector numProcessos = (StringArrayVector) retrievedDf.get("processos"); for (String num : numProcessos) { System.out.println(num); }
This ensures Renjin properly serializes and deserializes the data.frame between Java and R without treating it as an unrecognized external pointer.
内容的提问来源于stack exchange,提问作者neyanog

