Basic Syntax in R

In this article, we will discuss about how to begin with R programming language and introduce the basic concepts required in most of the programs that you write. 

Every programming language is associated with a typical syntax. The major elements of any programming language are the variables and their data types, the comments, and the keywords as well as how to display them on the screen. 

Variable Assignment Syntax in R

The variables can be assigned values, which may be string or numerical in nature. The data type is implicitly understood by the R interpreter. The assignment can be done by = , <- or -> operator

#using a string variable 
str1 <- "Hi!"
#printing the str1 variable

#using other numerical variable
54 -> var1
#printing the var1 variable

The output produced by the code is as follows : 

[1] "Hi!"
[1] 54

Syntax to Display Outputs on Console in R

Lines can be displayed in R using the in-built print() method. The print() method takes as a parameter both a variable or a value which is to be displayed onto the console. 

#using a string variable 
str1 <- "Hi!"
#printing the str1 variable

#using other string variable
str2 <- "FoxInfoTech"
#printing the str2 variable

#printing a string value
print("Basic Printing")

The code produces the following output : 

[1] "Hi!"
[1] "FoxInfoTech"
[1] "Basic Printing"

Creating Comments in R

Comments are statements in the piece of code that are just intended to enhance the understandability of any user who goes through the program. It increases the readability by explaining what exactly happens in the subsequence segment. R compiler basically ignores anything that is prepended with the symbol ‘#’. 

Comments are nowhere related to the logic of the code. Generally, comments are used to halt the program execution.

The comments can be broadly classified into two categories: single-line, which spans over a single statement, and multi-line, which span over a combination of lines in R.

The following code snippet illustrates the usage of multiline comments in R. Multiline comments can be depicted either by prepending each line with a ‘#’ symbol or to select the lines and press the shortcut “ command + shift + C”.

#assigning value to var num 
num <- 100

#first dividing the number by 10
#then multiplying by 2
#then adding 3 to the result 
fin_num <- ((num/10)*2)+3

#printing final result
cat("Final result : ",fin_num)

The output produced by the code is :

Final result: 23

Leave a Comment