| 1 |
package pp2.tools; |
| 2 |
|
| 3 |
import java.io.BufferedWriter; |
| 4 |
import java.io.File; |
| 5 |
import java.io.FileWriter; |
| 6 |
import java.io.IOException; |
| 7 |
|
| 8 |
/** |
| 9 |
* Class for the writing of R scripts and running these from the code |
| 10 |
* @author Stefanie Kaufmann |
| 11 |
* |
| 12 |
*/ |
| 13 |
public class RMethods { |
| 14 |
|
| 15 |
private static String installationPath; |
| 16 |
private File script; |
| 17 |
private BufferedWriter buff; |
| 18 |
private File outputFile = new File("temp.out"); |
| 19 |
|
| 20 |
public RMethods(String rPath) { |
| 21 |
installationPath = rPath; |
| 22 |
} |
| 23 |
|
| 24 |
/** |
| 25 |
* Start R with the previously written script |
| 26 |
*/ |
| 27 |
public void runR() { |
| 28 |
try { |
| 29 |
Runtime rt = java.lang.Runtime.getRuntime(); |
| 30 |
String separator = System.getProperty("file.separator"); |
| 31 |
//kickstart R with script file |
| 32 |
Process proc = rt.exec(installationPath+separator+"R CMD BATCH "+script.getAbsolutePath()+" "+outputFile.getAbsolutePath()); |
| 33 |
|
| 34 |
int exitVal = proc.waitFor(); |
| 35 |
System.out.println(exitVal); |
| 36 |
//remove temporary files |
| 37 |
script.deleteOnExit(); |
| 38 |
outputFile.deleteOnExit(); |
| 39 |
} catch (IOException e) { |
| 40 |
e.printStackTrace(); |
| 41 |
} catch (InterruptedException e) { |
| 42 |
e.printStackTrace(); |
| 43 |
} |
| 44 |
|
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Start to write the R script |
| 49 |
* @param filename The name of the script file |
| 50 |
*/ |
| 51 |
public void startRScript(String filename) { |
| 52 |
try { |
| 53 |
script = new File(filename); |
| 54 |
if(script.exists()) { |
| 55 |
script.delete(); |
| 56 |
script = new File(filename); |
| 57 |
} |
| 58 |
buff = new BufferedWriter(new FileWriter(script)); |
| 59 |
} catch (IOException e) { |
| 60 |
e.printStackTrace(); |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
/** |
| 65 |
* End the writing of the R script |
| 66 |
*/ |
| 67 |
public void endRScript() { |
| 68 |
try { |
| 69 |
buff.flush(); |
| 70 |
buff.close(); |
| 71 |
} catch (IOException e) { |
| 72 |
e.printStackTrace(); |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
/** |
| 77 |
* Write one line into the R script |
| 78 |
* @param line The line that will be written into the script |
| 79 |
*/ |
| 80 |
public void addLineToScript(String line) { |
| 81 |
try { |
| 82 |
buff.write(line+"\n"); |
| 83 |
} catch (IOException e) { |
| 84 |
e.printStackTrace(); |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
/** |
| 89 |
* Define the installation path of R |
| 90 |
* @param path The path of the bin directory where R is installed |
| 91 |
*/ |
| 92 |
public void setPath(String path) { |
| 93 |
installationPath = path; |
| 94 |
} |
| 95 |
|
| 96 |
|
| 97 |
} |