
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 Variablesx<-2L# By default x would be double if we store 2 in it so, L is used to denote an integer typetypeof(x)# Used to check the type of an object# doubley<-2.5typeof(y)# complexz<-3+2itypeof(z)# charactera<-”h”typeof(a)# logicalq<-TRUE#(OR) q<-Ttypeof(q)## Using VariablesA<-10B<-5C<-A+BC# To print object C# variable 1 → Commentsvar1<-2.5var2<-4result<-var1/var2resultsqrt(var2)# Inbuilt functiongreeting<-”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<5100>104==54!=55<=55>=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 Pythonresult<-!TRUEresultisTRUE(result)# while loopwhile(TRUE){print(“Hello”)}# In python identation is used whereas in R curly brackets are used# for loopfor(iin1:5){print(“HelloR”)}# 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:5for(iin5: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 0if(x>1){answer<-”Greaterthan1"}else{ if(x>=-1){ answer<-”Between -1 and 1"}else{answer<=”Lessthan-1" }}# The above structure is a nested if structure# Now let us implement else if:if(x>1){ answer<-”Greater than 1"}elseif(x>=-1){# In python we use elif() for else if()answer<-”Between-1and1" }else{ answer<=”Less than -1"}# To remove a variable the following command is used:rm(answer)
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)
For further actions, you may consider blocking this person and/orreporting abuse