DEV Community

Cover image for Core Programming principles in R
Ruthvik Raja M.V
Ruthvik Raja M.V

Posted on • Edited on

Core Programming principles in R

Hello everyone, let us dive into the basics of R programming:
Before getting started with R, download the necessary files like R Studio and R. But don't worry because I already wrote a blog on how to install R on macOS and Windows. The link to the blog is mentioned below:
https://dev.to/ruthvikraja_mv/installing-r-studio-on-mac-59hc
The following topics are covered in this article:

1.Types of variables.
2.Logical variables and operators.
3.Conditional and loop statements.

The R code for the above concepts are as follows:

######################## SECTION 1 ########################### # To execute code use -> command + return[Shortcut] in MAC # integer # In R Programming for assigning value to a variable the following symbol is used:  # <- [Which denotes an arrow] but “=” also works for assigning value to a variable. ## Types of Variables x<-2L # By default x would be double if we store 2 in it so, L is used to denote an integer type typeof(x) # Used to check the type of an object # double y<-2.5 typeof(y) # complex z<-3+2i typeof(z) # character a<-h typeof(a) # logical q<-TRUE #(OR) q<-T typeof(q) ## Using Variables A<-10 B<-5 C<-A+B C # To print object C # variable 1 → Comments var1<-2.5 var2<-4 result<-var1/var2 result sqrt(var2) # Inbuilt function greeting <-Hello typeof(greeting) # OR # class(greeting) name<-Bob message<-paste(greeting, name) message Hello + Bob # This throws an error whereas in Python it works -> print(“Hello”+”Bob”)  # Execute: # Logical Operators: 4<5 100>10 4==5 4!=5 5<=5 5>=5 # NOT Operator -> ! # OR Operator -> | # AND Operator -> & # isTRUE() # To find the remainder the following command is used in R: 5%%4 # Not 5%4 as we do in Python result <- !TRUE result isTRUE(result) # while loop while(TRUE){print(Hello)} # In python identation is used whereas in R curly brackets are used # for loop for(i in 1:5){ print(Hello R) } # Here i is an iterator and prints “Hello R” for 5 times # Here 1:5 represents a vector of numbers # Execute the following codes: 1:5 for(i in 5:10){ print(i) } # if statement # Let us generate one random normalized number: x<-rnorm(1) # Since, it is a normalized number the mean is 1 and standard deviation is 0 if(x>1){ answer<-Greater than 1" }else{ if(x>=-1){ answer<-”Between -1 and 1" } else{ answer<=Less than -1" } } # The above structure is a nested if structure # Now let us implement else if: if(x>1){ answer<-”Greater than 1" }else if(x>=-1){ # In python we use elif() for else if()  answer<-Between -1 and 1" }else{ answer<=”Less than -1" } # To remove a variable the following command is used: rm(answer) 
Enter fullscreen mode Exit fullscreen mode

Thank you, for spending your time on my post. Follow me for more updates on R.

The next post will be on Fundamentals of R[Section 2]

Happy coding…

Top comments (0)