0% found this document useful (0 votes)
11 views44 pages

Introduction to R Programming Basics

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views44 pages

Introduction to R Programming Basics

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

PROGRAMMING WITH

R
R Programming – A
beginning
⚫ R is an open source programming
language and software environment
for statistical computing and
graphics.

⚫ The R language is widely used


among statisticians and data miners
for developing statistical software
and data analytics tools

2
History of R

⚫ R project was created by Robert Gentleman and Ross


Ihaka, Department of Statistics, University of Auckland
(1995).
⚫ Modelled after S & S-plus, developed at AT&T labs in
late 1980s.
⚫ R ranks 11th in the TIOBE index, a measure of
programming language popularity.
History of R
• The official R software environment is a free
software environment within the GNU package, available under
the GNU General Public License.

• It is written primarily in C, Fortran, and R itself (partially self-


hosting).

• Multiple third-party graphical user interfaces are also available,


such as RStudio, an integrated development
environment, and Jupyter, a notebook interface.
STATISTICAL SOFTWARE’S
Why R is different from others?
SPSS SAS
Minitab MATLA
Statisti BR
ca ……………
………… ….
….. Programmi
Non- ng
Progra
mming
DATA SCIENTIST REQUIREMENTS
⚫R Programming

⚫ Python Coding

⚫ Hadoop Platform

⚫ Apache Spark
R VERSIONS
 R-4.1.2 (Bird Hippie)
 Released on 2021-11-01.
 86 megabytes, 32/64 bit

 R-4.0.5 (Shake and throw)


 released on 2021-03-31.

Use Current Version- R- 4.4.2


DOWNLOAD AND INSTALL R

Installing R on windows PC:

 Click on download option (R 4.4.2 for windows).


 Cran.R on Google
 Save this to the folder C:\R on your PC.
 When downloading is complete, close or minimize the Internet
browser.
 Double click on .exe in C:\R to install.

Installing R on Linux:

 sudo apt-get install r-base-core

Download R:
[Link]
INSTALLATION STEPS
INSTALLATION STEPS CONTD….
RStudio is an integrated development
environment (IDE) for R. It includes a
console, syntax-highlighting editor that
supports direct code execution, as well
as tools for plotting, history, debugging
and workspace management.

02-01- 1
2023 2
INSTALLING R STUDIO:

 Go to [Link] and click on the "Download R Studio" button.

 Click on "Download R Studio Desktop.“

 Click on the version recommended for your system, or the latest Windows
version, and save the executable file. Run the .exe file and follow the installation
instructions.

Download RStudio:
[Link]
VERSION

Get R version
R. Version()

Get R Studio version


R Studio: Toolbar at top > Help > About
RStudio
A TEST RUN WITH R IN WINDOWS
Double click the R icon on the Desktop and the R Console will
open. Wait while the program loads. You observe something like
this!!!!!!!

• You can type your own program at the prompt line >.
Overview of RStudio Interface

[Link] Pane:
•Top-left: Where scripts are written and saved.
create a new script (File -> New File -> R Script)
[Link]:
•Bottom-left: Where commands are typed and executed directly.
•type 2 + 2 in the Console and press Enter.
[Link]/History Pane:
•Top-right: Tracks variables, datasets, and command history.
•Example: Assign a variable x <- 5 and see how it appears in the Environment.
[Link]/Files/Help/Packages Pane:
•Bottom-right: View plots, installed packages, files, and access help.
•Example: Create a simple plot: plot(1:10, 1:10) and show it in the Plots tab.
R COMMAND IN INTEGRATED
ENVIRONMENT
GETTING HELP FROM R CONSOLE

🢝
[Link]()
🢝
help(topic)
🢝 ?topic
🢝 ??topic
Running R commands
1) Type directly in the Console:
Example: print("Hello, RStudio!")

2 ) Write and run code in the Source Pane:


x <- 5
y <- 10
sum <- x + y
print(sum)
T HINGS TO
REMEMBER……….
D ATA INP
UT
R AS A CALCULATOR
> 3+ # Addition
5 #
> 2-1
Subtraction
> 2*3
#
> 4/2
Multiplication
> 2^
# Division
3
Storing of values to # Power
Variables
> x=1
> x<-12
> 12->x
> 14->x
>y=1
> 1=
y
Error in 1 = y : invalid (do set) left-hand side to
assignment
HOW TO USE R FOR SIMPLE MATHS

> 3+5
> 12 + 3 / 4 – 5 +
3*8
> (12 + 3 / 4 – 5) +
Note
3*8
R ignores spaces
> pi * 2^3 – sqrt(4)
>factorial(4)
>log(2,10)
>log(2, base=10)
>log10(2)
>log(2)
HOW TO STORE RESULTS OF
CALCULATIONS FOR FUTURE
USE
> x = 3+5
>x
> y = 12 + 3 / 4 – 5 + 3*8
>y
>z= (12 + 3 / 4 – 5) + 3*8
>z
> A <- 6 + 8 # # no space should be
between < & -
> a # # Note: R is case sensitive
>A
FAMILIARIZE SOME
FUNCTIONS IN R
seq
rep
letters/LETTERS
scan
c
C FUNCTION AND SEQUENCE
FUNCTION
# 1 c function
# # # # c(1,2,4)
x= c(1,2,4)
x
# 2 Sequence function
# # # # seq(from = 1, to
= 10, by =2)
S = seq(from = 1, to =
10, by =2)
s
USING C COMMAND

> data1 = c(3, 6, 9, 12, 78, 34, 5, 7, 7) ##


numerical data
> [Link] = c(‘Mon’, ‘Tue’, “Wed”) # # Text
data
# # Single or double quote
both ok ##copy/paste into R console
may not work
> [Link] = c([Link], ‘Thu’, ‘Fri’)
SCAN COMMAND FOR MAKING
DATA
> data = # # data separated by Space /
scan()
Press # # Press Enter key
1: 4 5 7 8 twice to exit
5: 2 9 4
8: 3
9:
Console
> data
## Read 8 items
[1] 4 5 7 8 2 9
43
SCAN COMMAND FOR MAKING
DATA
> d3 = scan(what =
‘character’)
⚫>
1:
mon ⚫ d3[6]='sat
2:
tue
3: wed
⚫>' d3
thu
5
⚫ [1] "mon" "mon" "wed"
: "thu" NA "sat"
> d3 ⚫
[1] "mon" "tue" "wed" ⚫>
"thu"
> d3[2] ⚫ d3[2]='tue
[1]
"tue"
⚫>' d3[5] =
⚫ 'fri'
> d3[2]='mon'
⚫ > d3
> d3
⚫ [1] "mon" "tue" "wed"
[1] "mon" "mon" "wed"
"thu" "fri" "sat"
"thu"
IDENTIFIERS NAMING
Don't use underscores ( _ ) or hyphens ( - ) in identifiers.

The preferred form for variable names is all lower case letters
and words separated with dots ([Link]) but
variableName is also accepted.

Examples:
[Link]

GOOD avgClicks

OK avg_Clicks

BAD
CONCEPT OF WORKING
DIRECTORY
>getwd()
[1] "C:\Users\DSamanta\R\Database"

> setwd('D:\Data Analytics\Project\


Database)
> dir( # # working directory
) listing

>ls # # Workspace listing of


() objects

>rm(‘obje # # Remove an element “object”,


ct’) if exist
> rm(list = ##
ls()) Cleaning
READING DATA FROM
A DATA FILE
> setwd("D:/arpita/data analytics/my work") #Set the working directory
to file location

> getwd()

[1] "D:/arpita/data analytics/my work“


> dir()

[1] "[Link]" "DiningAtSFO" "TC-10- "[Link]


[Link]" "
"LatentView-DPL" rm(list=ls(all=TRUE)) # Refresh

> data=[Link]('[Link]', header = T, sep=",")


session

(data = [Link](‘[Link]', header = T, sep = ','))

> ls()

[1] "data"

> str(data)

'[Link]': 149 obs. of 5 variables:

$ X5.1 : num 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 5.4 ...

$ X3.5 : num 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 3.7 ...

$ X1.4 : num 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5
1.5 ...

$ X0.2 : num 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1
0.2 ...

$ [Link]: Factor w/ 3 levels "Iris-setosa",..: 1 1 1 1 1 1


1 1 1 1 ...
ACCESSING ELEMENTS
FROM A FILE
> data$X5.1
[1] 4.9 4.7 4.6 5.0 5.4 4.6 5.0 4.4 4.9 5.4 4.8 4.8 4.3 5.8 5.7
> data$X5.1[7]=5.2
> data$X5.1
[1] 4.9 4.7 4.6 5.0 5.4 4.6 5.2 4.4 4.9 5.4 4.8 4.8 4.3 5.8 5.7
#Note: This change has happened in workspace only not
in the file.
How to make it
permanent? [Link] /
[Link]
>[Link](data, file =‘iris_mod.csv', [Link] = FALSE,
sep = ',') If [Link] is TRUE, R adds one ID column in
the beginning of file. So its suggested to use [Link] =
FALSE option
>[Link](data, file ==‘iris_mod.csv', [Link] = TRUE)
DIFFERENT DATA ITEMS IN R
Vector

Matrix

Data

Frame List
VECTORS IN R
>x=c(1,2,3,4,56)
>x
> x[2]
> x = c(3, 4, NA, 5)
>mean(x)
[1] NA
>mean(x,
[Link]=T)
[1] 4
> x = c(3, 4, NULL,
5)
>mean(x)
[1] 4
MORE ON VECTORS IN R
>y = c(x,c(-1,5),x)
>length(x)
>length(y)
There are useful methods to create long vectors whose elements are in arithmetic
progression:
> x=1:20
>x

If the common difference is not 1 or -1 then we can use the seq function
> y=seq(2,5,0.3)
>y
[1] 2.0 2.3 2.6 2.9 3.2 3.5 3.8 4.1 4.4 4.7 5.0
> length(y)
[1] 11
MORE ON VECTORS IN R
> x=1:5
> mean(x) ⚫ It is very easy to
add/subtract/multiply/divid
[1] 3 e two vectors entry by
>x entry.
⚫ > y=c(0,3,4,0)
[1] 1 2 3 4 5
⚫ > x+y
> x^2
⚫ [1] 1 5 7 4 5
[1] 1 4 9 16 25 ⚫ > y=c(0,3,4,0,9)
> x+1 ⚫ > x+y
[1] 2 3 4 5 6 ⚫ [1] 1 5 7 4 14
> 2*x
⚫ Warning message:
⚫ In x + y : longer object
[1] 2 4 6 8 10 length is not a
> exp(sqrt(x)) multiple of shorter object
[1] 2.718282 4.113250 5.652234 length
7.389056 ⚫ > x=1:6
9.356469
⚫ > y=c(9,8)
⚫ > x+y
⚫ [1] 10 10 12 12 14 14
MATRICES IN R
Same data type/mode – number , character, logical
[Link] <- matrix(vector, nrow = r, ncol = c, byrow = FALSE, dimnames = list(char-
vector-rownames, char-
vector-col-names))
# # dimnames is optional argument, provides labels for rows & columns.
> y <- matrix(1:20, nrow = 4, ncol = 5)
>A = matrix(c(1,2,3,4),nrow=2,byrow=T)
>A
>A = matrix(c(1,2,3,4),ncol=2)
>B = matrix(2:7,nrow=2)
>C = matrix(5:2,ncol=2)
>mr <- matrix(1:20, nrow = 5, ncol = 4, byrow = T)
>mc <- matrix(1:20, nrow = 5, ncol = 4)
>mr
>mc
MORE ON MATRICES IN R
>dim(B) #Dimensi
>nrow(B) on
>ncol(B)
>A+C
>A-C
>A%*%C #Matrix multiplication. Where will be
>A*C the result? #Entry-wise multiplication
>t(A) #Transpose
>A[1,2]
>A[1,]
>B[1,c(2,
3)]
>B[,-1]
LISTS IN R
Vectors and matrices in R are two ways to work with a collection
of objects.

Lists provide a third method. Unlike a vector or a matrix a


list can hold different kinds of objects.

One entry in a list may be a number, while the next is a


matrix, while a third is
a character string (like "Hello R!").

Statistical functions of R usually return the result in the form of


lists. So we must know how to unpack a list using the $ symbol.
EXAMPLES OF LISTS IN R
>x = list(name="Arun Patel", nationality="Indian",
height=5.5, marks=c(95,45,80))

>names(x)
>x$name

>x$hei #abbreviations are


OK
>x$mar
ks
>x$m[2
]
DATA FRAME IN R
A data frame is more general than a matrix, in that different
columns can have
different modes (numeric, character, factor, etc.).
>d <- c(1,2,3,4)
>e <- c("red", "white", "red", NA)
>f <- c(TRUE,TRUE,TRUE,FALSE)
>myframe <- [Link](d,e,f)
>names(myframe) <- c("ID","Color","Passed") # Variable names
>myframe
>myframe[1 # Rows 1 , 2, 3 of data
:3,] frame
>myframe[, # Col 1,#Columns
>myframe[c("ID","Color")] 2 of data frame
ID and color from
1:2]
data frame
>myframe$ID # Variable ID in the data frame
FACTORS IN R
In R we can make a variable is nominal by making it a factor.

The factor stores the nominal values as a vector of integers in the


range [ 1... k] (where k is the number of unique values in the
nominal variable).

An internal vector of character strings (the original values) mapped


to these
integers.

# Example: variable gender with 20 "male"


entries and # 30 "female" entries
>gender <- c(rep("male",20), rep("female",
30))
>gender <- factor(gender)
# Stores gender as 20 1’s and 30 2’s
# 1=male, 2=female internally
(alphabetically) # R now treats gender
FUNCTIONS IN R

>g = function(x,y)
(x+2*y)/3
>g(1,2)
>g(2,1)

You might also like