I translated the grammar of R and Java [Updated from time to time]


What is this?

This is a comparison of the grammar of ** R **, which is a language specialized for processing and analysis of statistical data, with the format of ** Java **, which is a general-purpose language. Please refer to it so that those who understand Java can use it when they want to write R.

Required prerequisite knowledge (Java side)

・ Understand variable types (int, double, boolean, String, Object) ・ Understand multidimensional arrays ・ List and Map can be used (some sample code is used) ・ Extended for statement [Java 8] can be used (same as above)

If you say what you want to do with R, you will understand if this area is held down.

Required prerequisite knowledge (R side)

・ Installed R ・ I know that there is no need for a semicolon at the end of the sentence. ・ Yaruki

R-Java Opposite Dictionary

General-purpose grammar

Common to Java and R

・ ** Arithmetic operators other than division entanglement ** (+,-, *) -Comparison operators (<,>, <=,> =,! =) -Conditional logical operators(&&, ||), Logical operators(&, |),denial(!)


Java R
Substitution n = 0 n <- 0
Boolean value true, false TRUE, FALSE
(uppercase letter)
division(Integer quotient) a / b a %/% b*1
Surplus a % b a %% b
Exponentiation Math.pow(a, b) a ^ b
++a or a++
--a or a--
(a <- a+1)
not exist
Standard output System.out.println("Hello, world!"); print("Hello, world!")
Standard input Scanner class etc. readline("input :")*2
Definition of constants final int N = 0; not exist
Comment out //comment
/* comment */


if, for, switch statement


  System.out.println(statement is true);

for(int i=0;i<n;i++){
  System.out.println("for loop " + i);

  case 0:
    System.out.println("switch num=0");
  case 1:
    System.out.println("switch num=1");
    System.out.println("switch default");


  print("statement is TRUE")

for(i in 1:n){
  print(paste("for loop ", i-1))

  "0" = {print("switch num=0")},
  "1" = {print("switch num=1")},
  {print("switch default")}

Annotation As in the standard output in the R for statement, it is not possible to output a string and a numerical value connected by + (strictly, it is not recommended even in Java). Use the paste () method. The {} in each statement of the R switch statement can be omitted if the content is only one statement.

How to call each element of a two-dimensional array (R: matrix)


int[][] a = new int[4][4];


a <- matrix(ncol=4, nrow=4)

Both make almost the same appearance (there are differences such as 0 if the initial value is java and NA if it is R. In the case of R, the value taken by the contents of the matrix type is a numerical value. Not exclusively) How to refer to each element of this matrix is as follows.

Java R
1 element reference a[2][3] a[3,4]
1 element reference a[3][0] a[4]Ora[4,1]
1 can be omitted only at the beginning of the line
Line reference a[1] a[2,]
Column reference - a[,2]

Eliminate the use of for statements (apply family)

If you don't use the for statement, it's like R for one person, but it doesn't explain much, so let's see what the apply family is doing in opposition to Java.

Apply a function to each element of a multidimensional array


//Array generation and initialization from here
int[][] mtrx = new int[4][4];
for(int i=0;i<4;i++){
  for(int j=0;j<4;i++){
    mtrx[i][j] = i * 4 + j;
//So far
//Preparation of functions to be applied repeatedly from here
int add(int i){
  return i+1;
//So far
//From here, scan the array and apply the function
for(int i=0;i<4;i++){
  for(int j=0;j<4;i++){
    mtrx[i][j] = add(mtrx[i][j]);
//So far

A two-dimensional array containing numbers from 0 to 15 is generated, and 1 is added to each element (of course, to explain in comparison, this is a hair-raising ~ ~ redundant writing style. ).


#Matrix generation and initialization from here
a <- matrix(c(1:16), ncol=4, nrow=4, byrow=TRUE)
#So far
#Preparation of functions to be applied repeatedly from here
add <- function(i){
#So far
#From here, scanning the matrix and applying the function
apply(a, c(1,2), add)
#So far

It can be written very simply like this. I've created a function that runs repeatedly here, but you can use any of the available functions (for example, sqrt gives you a matrix with the square roots of all the elements).

Annotation -The byrow option of thematrix ()function is an option to arrange the source vector (c (1:16) in this example) to be a matrix in row units. The default is FALSE, so this code will generate a transposed version of the resulting matrix. -The second option (c (1: 2)) of the ʻapply ()` function specifies the scope. Do the same with 1 for "all rows" and 2 for "all columns". ** If you just want to write a for loop on a 2D array, you don't have to worry about it at all, so don't mess with it carelessly **. Specifically, the following two codes do roughly the same thing. R is really just this, not overwriting.


int sum(int[] arr){  //A function that gives the sum of arrays. R comes standard
  int sum = 0;
  for(int i : arr){
    sum += i;
  return sum;

int[] sum_arr = new int[4];
for(int i=0;i<4;i++){
  sum_arr[i] = sum(mtrx[i]);  //Sum for all lines()Apply function


apply(a, 1, sum)

Apply function to each element of HashMap (lapply)

First, it is necessary to understand that list type variables in R ** do not need to have the same type of values held inside **. In other words, it is like declaring that Java Map handles object types unless you declare anything in particular.


Map<String, Object> a = new HashMap<>();
a.put("i", 123);
a.put("d", 4.56d);
a.put("b", false);


a <- list(i = 123, d = 4.56, b = FALSE)

In this way, it is possible to have an integer type, a double precision floating point type, and a logical type at the same time. lapply performs processing on a list or matrix and ** returns the result as a list **.


Map<String, Object> a = new HashMap<>();
a.put("i", 123);
a.put("d", 4.56d);
a.put("b", false);

for(Object o : a.values()){
}    //Compile error!


a <- list(i = 123, d = 4.56, b = FALSE)

lapply(a, add) #add()The function is apply.Diverted from R

Since the argument of the add () function defined in apply.java is int type, the above code cannot be executed in Java. But in R there is no need for a type declaration and the variables are automatically matched to the largest type so you can execute this code (treated as FALSE = 0, TRUE = 1) and print: To.

> lapply(a, add)
[1] 124

[1] 5.56

[1] 1

You can use lapply for 2D arrays, but it will be awkward unless you have to output as a list type. You can assume that it is such a function. For the 4x4 matrix generated by apply.java (apply.R), the following two lapply () output almost the same thing.


Map<String, Integer> lapply(int[][] arr){
  Map<String, Integer> a = new HashMap<>();
  for(int i=0;i<arr[0].length;i++){
    for(int j=0;j<arr.length;j++){
      a.put(String.valueOf(i * 4 + j + 1), add(arr[j][i]));
      //arr[i][j]Not arr[j][i]Note that
      //In R, scanning for 2D arrays is done column by column
  return a;


lapply(a, add)  
#apply.Add to all elements of a as in R()Apply, but
#The appearance of the output result is apply.It's totally different from R. Please run and check

Annotation -In lapply3.java, Map <String, Integer> is used as the return type, but in reality, the number from 1 to 16 (cast to String type) is entered in Key, so it looks redundant. Since the R matrix can have names for row numbers and column numbers, such a description is used because the value entered in Key may not be a numerical value if a strict correspondence is attempted.

String processing

Overall, R is not good at character string processing. If a large amount of character string processing is required for data preprocessing, consider using another language or using spreadsheet software first.



//Example 1
String str = "Hello" + " " + "world!";  //Not recommended as it consumes more memory

//Example 2
StringBuilder builder = new StringBuilder();
builder.append(" ");
String str = builder.toString();


str <- paste("Hello", " ", "world!")

Supplementary provisions

Execution environment of the code in this page

Java -Java version: 1.8.0_231 -IDE: Intellij IDEA Community Edition 2019.2

R -R version: R x64 3.6.0 -IDE: R Studio 1.2.1335

Please refer to it if you cannot execute it well.

Recommended Posts

I translated the grammar of R and Java [Updated from time to time]
I tried to summarize the basics of kotlin and java
From fledgling Java (3 years) to Node.js (4 years). And the impression of returning to Java
I tried to summarize the methods of Java String and StringBuilder
Run R from Java I want to run rJava
I compared the characteristics of Java and .NET
The date time of java8 has been updated
[Java] I want to calculate the difference from the date
How to write Scala from the perspective of Java
Java language from the perspective of Kotlin and C #
[Eclipse] Summary of environment settings * Updated from time to time
I summarized the types and basics of Java exceptions
I didn't understand the behavior of Java Scanner and .nextLine ().
[JDBC] I tried to access the SQLite3 database from Java.
Command to check the number and status of Java threads
I tried to summarize the basic grammar of Ruby briefly
[Java] Use ResolverStyle.LENIENT to handle the date and time nicely
[Java] I thought about the merits and uses of "interface"
In Java, I want to trim multiple specified characters from only the beginning and end.
The road from JavaScript to Java
Memorandum Poem (updated from time to time)
[Java] Various summaries attached to the heads of classes and members
I want to return to the previous screen with kotlin and java!
Summary of results of research on object orientation [Updated from time to time]
[Java] How to convert from String to Path type and get the path
Let's summarize the Java 8 grammar from the perspective of an iOS engineer
Introduction to java for the first time # 2
Convert from java UTC time to JST time
[day: 5] I summarized the basics of Java
What are the updated features of java 13
[Java] I personally summarized the basic grammar.
Output of the book "Introduction to Java"
The story of forgetting to close a file in Java and failing
I want to display images with REST Controller of Java and Spring!
[Java] How to get the current date and time and specify the display format
[Ruby] I want to extract only the value of the hash and only the key
Confirmation and refactoring of the flow from request to controller in [httpclient]
I want to pass the argument of Annotation and the argument of the calling method to aspect
[Java improvement case] How to reach the limit of self-study and beyond
I want to get the field name of the [Java] field. (Old tale tone)
I tried to measure and compare the speed of GraalVM with JMH
By checking the operation of Java on linux, I was able to understand compilation and hierarchical understanding.
[Reverse lookup] Spring Security (updated from time to time)
I received the data of the journey (diary application) in Java and visualized it # 001
[Promotion of Ruby comprehension (1)] When switching from Java to Ruby, first understand the difference.
I want to control the start / stop of servers and databases with Alexa
[Rails] I tried to raise the Rails version from 5.0 to 5.2
SpringBoot useful site collection (updated from time to time)
[Java] Set the time from the browser with jsoup
Points I stumbled upon when creating an Android application [Updated from time to time]
[Java] Get and display the date 10 days later using the Time API added from Java 8.
[Java] Program example to get the maximum and minimum values from an array
[Java] The confusing part of String and StringBuilder
I want to var_dump the contents of the intent
Differences between Java, C # and JavaScript (how to determine the degree of obesity)
[Updated from time to time] Links that are indebted
I want you to use Scala as Better Java for the time being
I want to get only the time from Time type data ...! [Strftime] * Additional notes
I want to write quickly from java to sqlite
I touched on the new features of Java 15
[Java] How to get the authority of the folder