0% found this document useful (0 votes)
59 views10 pages

Unit-2-Start Learning R

R is an open source programming language that is popular for statistical analysis and data visualization. It runs on Windows, MacOS, and Linux. This document provides an introduction to downloading and installing R, working with the R session, assigning values to variables, getting help, exiting the session, listing and removing objects, getting/setting the working directory, comments, reserved words, variables, constants, basic data types, operators, functions, and taking input from the user.

Uploaded by

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

Unit-2-Start Learning R

R is an open source programming language that is popular for statistical analysis and data visualization. It runs on Windows, MacOS, and Linux. This document provides an introduction to downloading and installing R, working with the R session, assigning values to variables, getting help, exiting the session, listing and removing objects, getting/setting the working directory, comments, reserved words, variables, constants, basic data types, operators, functions, and taking input from the user.

Uploaded by

liman69609
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

R Introduction

1. R is open source and free!


2. R is popular - and increasing in popularity
3. R runs on all platforms
4. R is being used by the biggest tech giants

Downloading and Installing R


• http://cran.r-project.org

Working with R session


Assigning value
> a=5
> b=6
> c=a+b
> c
The value of the variable 'c' is printed as,
[1] 11

Get help inside R session


> help("if")
> help.search(“histograms")
> ??”histograms”

Exit the R session


> quit()
Saving the R session
When we work in R, the R objects we created and loaded are stored in a memory portion
called workspace. When we say 'no' to saving the workspace, we all these objects are
wiped out from the workspace memory. If we say 'yes', they are saved into a file called
".RData" is written to the present working directory.

Listing the objects in the current R session


> ls()
[1] "a" "b" "c"

Removing objects from the current R session


> a=5
> b=6
> c=8
> sum = a+b+c
sum [1] 19
> ls()
[1] "a" "b" "c" "sum"

> rm(list=c("sum"))
> ls()
[1] "a" "b" "c"
>
> rm(list = ls())
> ls() character(0)
Getting and setting the current working directories
> getwd()
[1] "/home/user"
Similarly, we can set the current wor directory by calling setwd() function:
> setwd("/home/user/prog")

Getting file information from R session


> list.files()
This lists all the files in the current directory.

In case we need information on a specific file,


> file.info("filename")

Comments
Single comment is written using # in the beginning of the statement as follows:
# My first program in R Programming

R does not support multi-line comments but you can perform a trick which is something as follows:
if(FALSE)
{
"This is a demo for multi-line comments and it should be put inside either a single of double quote"
}
myString <- "Hello, World!" print ( myString)
Though above comments will be executed by R interpreter, they will not interfere with
your actual program. You should put such comments inside, either single or double quote.

R Reserved Words
if else repeat while function
for in next break TRUE
FALSE NULL Inf NaN NA
NA_integer_ NA_real_ NA_complex_ NA_character_ ...

This list can be viewed by typing


> help(reserved)
or
?reserved

 TRUE and FALSE are the logical constants in R.


 NULL represents the absence of a value or an undefined value.
 Inf is for "Infinity", for example when 1 is divided by 0
 NaN is for "Not a Number", for example when 0 is divided by 0.
 NA stands for "Not Available" and is used to represent missing values.
 R is a case sensitive language. Which mean that TRUE and True are not the same.
Variables in R
Variables are used to store data, whose value can be changed according to our need. Unique name
given to variable (function and objects as well) is identifier.
Rules for writing Identifiers in R
1. Identifiers can be a combination of letters, digits, period (.) and underscore (_).
2. It must start with a letter or a period. If it starts with a period, it cannot be followed by a digit.
3. Reserved words in R cannot be used as identifiers.
Valid identifiers in R
total, Sum, .fine.with.dot, this_is_acceptable, Number5
Invalid identifiers in R
tot@l, 5um, _fine, TRUE, .0ne

Constants in R
Constants, as the name suggests, are entities whose value cannot be altered. Basic types of constant
are numeric constants and character constants.
Numeric Constants
 All numbers fall under this category. They can be of type integer, double or complex.
 It can be checked with the typeof() function.
 Numeric constants followed by L are regarded as integer and those followed by i are regarded as
complex.
> typeof(5)
[1] "double"
> typeof(5L)
[1] "integer"
> typeof(5i)
[1] "complex"
 Numeric constants preceded by 0x or 0X are interpreted as hexadecimal numbers.
> 0xff [1] 255
> 0XF + 1 [1] 16

Character Constants
Character constants can be represented using either single quotes (') or double quotes (") as
delimiters.
> 'example'
[1] "example"
> typeof("5")
[1] "character"

Built-in Constants
Some of the built-in constants defined in R along with their values is shown below.
> LETTERS
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q"
"R" "S"
[20] "T" "U" "V" "W" "X" "Y" "Z"
> letters
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q"
"r" "s"
[20] "t" "u" "v" "w" "x" "y" "z"
> pi
[1] 3.141593
Example: Hello Gacr Program
> # We can use the print() function
> print("Hello Gacr!")
[1] "Hello Gacr!"

> # Quotes can be suppressed in the output


> print("Hello Gacr!", quote = FALSE)
[1] Hello Gacr!

> # If there are more than 1 item, we can concatenate using paste()
> print(paste("How","are","you?"))
[1] "How are you?"

Basic data types in R


 To make the best of the R language, you'll need a strong understanding of the basic data
types and data structures and how to operate on those.
 Very Important to understand because these are the things you will manipulate on a day-
to-day basis in R. Most common source of frustration among beginners.
 Everything in R is an object.
 R has 5 basic atomic classes
 logical (e.g., TRUE, FALSE)
 integer (e.g,, 2L, as.integer(3))
 numeric (real or decimal) (e.g, 2, 2.0, pi)
 complex (e.g, 1 + 0i, 1 + 4i)
 character (e.g, "a", "swc")
 R also has many data structures. These include
 vector
 list
 matrix
 data frame
 factors (we will avoid these, but they have their uses)
 tables

R Operators
R has several operators to perform tasks including arithmetic, logical and bitwise operations.
R has many operators to carry out different mathematical and logical operations. Operators in R can
mainly be classified into the following categories.
Arithmetic operators
Relational operators
Logical operators
Assignment operators

R Arithmetic Operators
These operators are used to carry out mathematical operations like addition and multiplication. Here
is a list of arithmetic operators available in R.

Arithmetic Operators in R
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
^ Exponent
%% Modulus (Remainder from division)
%/% Integer Division

Example
> x <- 5
> y <- 16
> x+y [1]
21

> x-y [1] -


11
> x*y [1]
80
> y/x [1]
3.2
> y%/%x
[1] 3
> y%%x
[1] 1
> y^x
[1] 1048576

R Relational Operators
Relational Operators in R
Operator Description
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to

Example
> x <- 5
> y <- 16
> x<y
[1] TRUE

> x>y
[1] FALSE

> x<=5
[1] TRUE

> y>=20
[1] FALSE

> y == 16
[1] TRUE

> x != 5
[1] FALSE
R Logical Operators
Logical Operators in R
Operator Description
! Logical NOT
& Element-wise logical AND
&& Logical AND
| Element-wise logical OR
|| Logical OR

R Assignment Operators
Assignment Operators in R
Operator Description
<-, <<-, = Leftwards assignment
->, ->> Rightwards assignment

Use of print() function


> print("Hello World!")
[1] "Hello World!"

> # Quotes can be suppressed in the output


> print("Hello World!", quote = FALSE)
[1] Hello World!

> # If there are more than 1 item, we can concatenate using paste()
> print(paste("How","are","you?"))
[1] "How are you?"

Take input from user


 readline() function is used to take input from the user (terminal).
 This function will return a single element character vector.

Example:
my.name <- readline(prompt="Enter name: ")
my.age <- readline(prompt="Enter age: ")

# convert character into integer


my.age <- as.integer(my.age)
print(paste("Hi,", my.name, "next year you will be", my.age+1,
"years old."))
Output
Enter name: Mary
Enter age: 17
[1] "Hi, Mary next year you will be 18 years old."

Example: Multiplication Table


num = as.integer(readline(prompt = "Enter a number: "))
for(i in 1:10)
{
print(paste(num,'x', i, '=', num*i))
}
Example: Find the factorial of a number
# take input from the user
num = as.integer(readline(prompt="Enter a number: "))
factorial = 1
# check is the number is negative, positive or zero
if(num < 0)
{
print("Sorry, factorial does not exist for negative numbers")
} else if(num == 0)
{
print("The factorial of 0 is 1")
} else
{
for(i in 1:num)
{
factorial = factorial * i
}
print(paste("The factorial of", num ,"is",factorial))
}
Output
Enter a number: 8
[1] "The factorial of 8 is 40320"
 We can also use the built-in function factorial() for this.
> factorial(8)
[1] 40320

R Functions
Syntax
func_name <- function (argument)
{
statement
}

Example
pow <- function(x, y)
{
result <- x^y
print(paste(x,"raised to the power", y, "is", result))
}

How to call a function?


>pow(8, 2)
[1] "8 raised to the power 2 is 64"

> pow(2, 8)
[1] "2 raised to the power 8 is 256"

Here, the arguments used in the function declaration (x and y) are called formal arguments and
those used while calling the function are called actual arguments.
Named Arguments
 In the above function calls, the argument matching of formal argument to the actual arguments
takes place in positional order.
 This means that, in the call pow(8,2), the formal arguments x and y are assigned 8 and 2
respectively.
 We can also call the function using named arguments.
 When calling a function in this way, the order of the actual arguments doesn't matter. For
example, all of the function calls given below are equivalent.
> pow(8, 2)
[1] "8 raised to the power 2 is 64"
> pow(x = 8, y = 2)
[1] "8 raised to the power 2 is 64"
> pow(y = 2, x = 8)
[1] "8 raised to the power 2 is 64"

Furthermore, we can use named and unnamed arguments in a single call.

In such case, all the named arguments are matched first and then the remaining unnamed arguments
are matched in a positional order.
> pow(x=8, 2)
[1] "8 raised to the power 2 is 64"

> pow(2, x=8)


[1] "8 raised to the power 2 is 64"

Default Values for Arguments


We can assign default values to arguments in a function in R.
pow <- function(x, y = 2)
{
# function to print x raised to the power y
result <- x^y
print(paste(x,"raised to the power", y, "is", result))
}
The use of default value to an argument makes it optional when calling the function.
> pow(3)
[1] "3 raised to the power 2 is 9"
> pow(3,1)
[1] "3 raised to the power 1 is 3"
R Return Value from Function
return(expression)

Example : Given number is positive, negative or zero.


check <- function(x)
{
if (x > 0)
{
result <- "Positive"
}
else if (x < 0)
{
result <- "Negative"
}
else
{
result <- "Zero"
}
return(result)
}

Sample runs
> check(1)
[1] "Positive"

> check(-10)
[1] "Negative"

> check(0)
[1] "Zero"

Functions without return()


If there are no explicit returns from a function, the value of the last evaluated expression is returned
automatically in R.

check <- function(x)


{
if (x > 0)
{
result <- "Positive"
}
else if (x < 0)
{
result <- "Negative"
}
else
{
result <- "Zero"
}
result
}
We generally use explicit return() functions to return a value immediately from a function.

check <- function(x)


{
if (x>0)
{
return("Positive")
}
else if (x<0)
{
return("Negative")
}
else
{
return("Zero")
}
}
Multiple Returns
The return() function can return only a single object. If we want to return multiple values in R, we can
use a list (or other objects) and return it.
Example
multi_return <- function()
{
my_list <- list("color" = "red", "size" = 20, "shape" = "round")
return(my_list)
}

Here, we create a list my_list with multiple elements and return this single list.

> a <- multi_return()


> a$color
[1] "red"

> a$size
[1] 20

> a$shape
[1] "round"

R Recursive Function
Example
recursive.factorial <- function(x)
{
if (x==0) return(1)
else return(x * recursive.factorial(x-1))
}
> recursive.factorial(0)
[1] 1
> recursive.factorial(5) [1]
120
> recursive.factorial(7) [1]
5040

You might also like