Quick Contact


    R Basic Syntax

    R Programming is a very popular programming language which is broadly used in data analysis. The way in which we define its code is quite simple. The “Hello World!” is the basic program for all the languages, and now we will understand the syntax of R programming with “Hello world” program. We can write our code either in command prompt, or we can use an R script file.

    Basic Program of Hello World

    Once you set up the environment for R, it is easy to start the R command prompt by simply typing the following command at your command prompt:

    $ R

    This command will let you launch the R interpreter with a symbol like this ‘>’, and you start writing the program using command prompt:

    > newStr <- "Hello - World!"

    > print (newStr)

    [1] “Hello – World!”

    Now write the same program using R script:

    Generally, you will write your programs in script files, and then you implement those scripts at your command prompt using the help of an R interpreter called Rscript. Here is the Hello World Script:

    myString <- "Hello, World!"

    print ( myString)

    Save the code you have written in a file “helo.R” and execute this code at Linux command prompt using the below-mentioned command. Whatever be your OS, either Windows or other systems, the command syntax will stay the same.

    $ Rscript test.R

    Comments in R Programming

    Comments are like helping text within your R source code, and these statements get ignored by the interpreter while running your actual program. The single-line comment is written with the starting symbol ‘#’ at the beginning of the statement as given below:

    # My first R program is Hello – World

    It can be disadvantageous that R does not support multi-line comment, but you can perform a trick, and its code will look something like this:

    if(FALSE) {

    “This is an example of how to write multi-line comments.

    }

    newStr <- "Hello - World!"

    print ( newStr)

    It is to be noted that the strings while using a Multi-line comment should have to be put inside either Single quote or Double Quote.

    Example 2

    The C function in R does something completely different than in C, and they are often used in R programming.

    Example:

    1:4 + 5:8 #look, no loops!

    ## Output will be: [1] 6 8 10 12 14

    c(1, 2, 6, 8, 10) + c(0, 1, 5, 7, 9)

    ## Output will be: [1] 1 3 11 15 19

    The colon operator and the c function are used almost everywhere in R code, so it’s good to practice using them.

    Copyright 1999- Ducat Creative, All rights reserved.