0% found this document useful (0 votes)
9 views13 pages

R - I Unit

The document provides an overview of various concepts and functions in R programming, including assignment operators, vectors, matrices, and data manipulation techniques. It covers how to create and manipulate vectors and matrices, perform operations like sorting, indexing, and extracting elements, as well as using functions like seq(), rep(), and diag(). Additionally, it discusses the differences between ggplot2 and base R graphics for plotting, along with examples for better understanding.

Uploaded by

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

R - I Unit

The document provides an overview of various concepts and functions in R programming, including assignment operators, vectors, matrices, and data manipulation techniques. It covers how to create and manipulate vectors and matrices, perform operations like sorting, indexing, and extracting elements, as well as using functions like seq(), rep(), and diag(). Additionally, it discusses the differences between ggplot2 and base R graphics for plotting, along with examples for better understanding.

Uploaded by

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

Statistical Computing and R Programming– I UNIT

2 marks:
1. What are the two ways of assignment operators in R? Give an example.
In R, there are two ways of assignment operators: <- and =. For example:
• Using <- : x <- 5 assigns the value 5 to the variable x.
• Using = : y = 10 assigns the value 10 to the variable y.
2. What is vector? Give an example to create a vector?
A vector in R is a one-dimensional array that can contain elements of the same data type. To create
a vector, you can use the c() function. For example:
• Numeric vector: my_vector <- c(1, 2, 3, 4, 5)
• Character vector: fruits <- c("apple", "banana", "cherry")

3. How do you find length of a vector? Give an example.


To find the length of a vector in R, you can use the length() function. For example:
vec <- c(1, 2, 3, 4, 5)
length(vec)

will return 5.
4. How do you sort a vector in descending order? Give an example.
To sort a vector in descending order in R, you can use the sort() function with the decreasing
parameter set to TRUE. For example:
vec <- c(5, 2, 8, 1, 3)
sorted_vec <- sort(vec, decreasing = TRUE)

will give you a vector sorted in descending order.


5. Create and store a sequence of values from 5 to −11 that progresses in steps of 0.3.
To create and store a sequence of values in R, you can use the seq() function. Here's how you can
create a sequence from 5 to -11 in steps of 0.3.
my_sequence <- seq(5, -11, by = -0.3)

6. Let vector, myvect with elements 5, -3,4,4,4,8,10,40221, -8,1. Write code to delete last
element from it.
To delete the last element from a vector in R, you can use the indexing with a negative value. For
example:
my_vect <- c(5,-3,4,4,4,8,10,40221,-8,1)
my_vect[-length(my_vect)]
5 -3 4 4 4 8 10 40221 -8

7. Write the purpose of negative indexing in vectors? Give an example.


Negative indexing in vectors is used to exclude elements from the vector. For example:
my_vector <- c(1, 2, 3, 4, 5)
my_vector[-3]

will return a vector without the third element, which is 3.


8. If baz <- c(1,-1,0.5,-0.5) and qux <- 3, find the value of baz+qux.
baz+qux will add 3 to each element of the baz vector.
baz <- c(1, -1, 0.5, -0.5)
qux <- 3
baz + qux
4.0 2.0 3.5 2.5

9. What is the use of cbind and rbind functions in Matrix? Give an example.
cbind and rbind are functions in R used to combine vectors or matrices into a matrix.
cbind combines objects by columns, and rbind combines objects by rows.
Eg : x <- c(1, 2, 3)
y <- c(4, 5, 6)
cbind(x, y)
1 4
2 5
3 6

10. How do you find the dimension of the matrix? Give an example.
To find the dimension of a matrix in R, you can use the dim() function.
For example: mat <- matrix(1:6, nrow = 2, ncol = 3)
dim(mat)
2 3 it's a 2x3 matrix.
11. Construct a 4 × 2 matrix that is filled row-wise with the values 4.3, 3.1, 8.2, 8.2, 3.2, 0.9,
1.6, and 6.5, in that order using R command.
To construct a 4x2 matrix filled row-wise with the specified values, you can use the matrix()
function in R.
mat <- matrix(c(4.3,3.1,8.2,8.2,3.2,0.9,1.6,6.5), nrow=4, ncol=2, byrow=TRUE)
mat

12. What is the use of diag command in R? Give an example.


The diag() function in R is used to create a diagonal matrix or extract the diagonal elements from a
matrix. For example:
To create a diagonal matrix: mat <- diag(1:3)
1 0 0
0 2 0
0 0 3
To extract the diagonal elements from a matrix mat: diag(mat)
1 2 3

13. Write proper code to replace the third column of matrix B with the values in the third row
of B.
To replace the third column of matrix B with the values from the third row of B, you can use
indexing as follows:
B[, 3] <- B[3, ]
14. Write an example to find transpose and inverse of a matrix using R command?
t() function is used to find the transpose and solve() function is used to find the inverse of a matrix.
Eg: mat<-matrix(c(1,2,3,4), nrow=2, ncol=2)
t(mat)
1 2
3 4
solve(mat)
-2 1.5
1 -0.5

15. What is the difference between & and && in R? Give an example.
In R, & is a bitwise AND operator, and && is a logical AND operator. Here's an example:
a <- TRUE
b <- FALSE
a & b will return FALSE, and a && b will also return FALSE.

16. Write R command to store the vector c(8,8,4,4,5,1,5,6,6,8) as bar. Identify the elements less
than or equal to 6 AND not equal to 4.
bar <- c(8, 8, 4, 4, 5, 1, 5, 6, 6, 8)
bar [ bar <= 6 & bar != 4 ]
5 1 5 6 6

17. How do you count the number of individual characters in a string? Give an example.
To count the number of individual characters in a string in R, you can use the nchar() function. For
example:
text <- "Hello, World!"
nchar(text)
13

18. What is levels function in R? Give an example.


The levels() function in R is used with factors to get the levels (distinct categories) of a factor
variable. For example:
gender <- factor(c("Male", "Female", "Male", "Male", "Female"))
levels(gender)
"Female" "Male".

19. What is list in R? Give an example.


A list in R is a data structure that can hold a collection of objects (vectors, data frames, etc.) of
different types. For example:
my_list <- list(name = "John", age = 30, scores = c(85, 90, 78))
my_list
$name
"John"
$age
30
$scores
85 90 78
20. What is list slicing in lists? Give an example.
In R, you can select multiple list items at once using single square brackets. This is known as list
slicing.
Eg: thislist <- list("apple", c(T,F,T,T), c(0,1,2,3))
thislist[c(2,3)]
TRUE FALSE TRUE TRUE
0 1 2 3

21. How do you name list contents? Give an example.


You can name list contents in R by using the names() function or directly when creating the list.
Using names() : my_list <- list(1, 2, 3)
names(my_list) <- c("A", "B", "C")
Directly : my_list <- list(A = 1, B = 2, C = 3)

22. What is the purpose of attributes and class functions? Give an example.
The attributes() function is used to attach metadata to R objects. The class() function is used to
specify the class of an object. For example:
x <- c(1, 2, 3)
attributes(x) <- list(comment = "Sample vector")
class(x) <- "my_class"

23. What is the difference between ggplot2 and base R graphics create plots? Give an
example.
ggplot2 is a popular data visualization package in R that provides a more flexible and layered
approach to creating plots compared to base R graphics. ggplot2 allows you to build complex,
customized plots. Base R graphics are more simplistic and are created using functions like plot().
Here's a simple example:
library(ggplot2)
ggplot(data = df, aes(x=category, y=values)) + geom_bar(stat = "identity")
df <- data.frame(category = c("A", "B", "C"), values = c(10, 15, 8))
barplot(df$values, names.arg = df$category)

Long Answer Questions


1. Explain seq, rep and length functions on vectors with example.
seq() : It is used to create sequences of numbers. It can be used to generate a sequence from a
starting value to an ending value, with a specified increment.
Eg: seq(1,10,by=2)
1,3,5,7,9

rep() : It is used to replicate elements in a vector. It takes two main arguments: the vector to be
replicated and the number of times to repeat it.
Eg: vector <- c(1,2,3)
rep(vector,times= ) # Repeats the vector three times
1,2,3,1,2,3,1,2,3
length() : It is used to determine the length of a vector, which is the number of elements it contains.
Eg: my_vector <- c(4,7,2,9,5)
length(my_vector)
5

2. Repeat the vector c (-1, 3, -5, 7, -9) twice, with each element repeated 10 times, and store the
result. Display the result sorted from largest to smallest.
c <- c(-1,3,-5,7,-9)
repeated_c <- rep(c, times = 2)
result_vector <- rep(repeated_c, each = 10)
sorted_vector <- sort(result_vector, decreasing = TRUE)
sorted_vector

3. How do you extract elements from vectors? Explain it using individual and vector of
indexes with example?
Individual Indexing: You can extract elements from a vector by specifying the index of the
element you want.
Eg: my_vector <- c(10, 20, 30, 40, 50)
element1 <- my_vector[1] # Extracts the first element (10)
element3 <- my_vector[3] # Extracts the third element (30)

Vector of Indexes: You can extract multiple elements by providing a vector of indices.
Eg: indices <- c(2, 4)
elements <- my_vector[indices] # Extracts the 2nd and 4th elements (20, 40)

4. How do you create matrix in R? Explain with its necessary attributes? Give an example.
To create a matrix in R, you can use the matrix() function. The necessary attributes are :
data : The vector containing the data elements.
nrow : The number of rows in the matrix.
ncol : The number of columns in the matrix.
byrow: If byrow = TRUE, data is filled row-wise; if byrow = FALSE (default), data is filled
column-wise.
Eg: data <- 1:4
mat <- matrix(data, nrow = 2, ncol = 2, byrow = TRUE)
mat
1 2
3 4
5. Do the following operations on a square matrix.
a. Retrieve third and first rows of A, in that order, and from those rows, second and third
column elements.
b. Retrieve diagonal elements
c. Delete second column of the matrix.
a. A <- matrix(1:9, nrow = 3)
rows <- c(3, 1)
cols <- c(2, 3)
result <- A[rows, cols]
result
6 9
4 7
b. diag(A)
1 5 9
c. A[ , -2]
1 7
2 8
3 9

6. Explain row, column, and diagonal extractions of matrix elements with example.
Row extraction: You can extract specific rows from a matrix by specifying the row indices.

Eg: mat <- matrix(1:9, nrow = 3)


row2 <- mat[2, ] # Extracts the second column
row2
2 5 8

Column extraction: You can extract specific columns from a matrix by specifying column indices.

Eg: mat <- matrix(1:9, nrow = 3)


col3 <- mat[, 3] # Extracts the third column
col3
7 8 9

Diagonal extraction: To extract the diagonal elements of a matrix, you can use the diag() function.

Eg : mat <- matrix(1:9, nrow = 3)


diag(mat)
1 5 9

7. How do you omit and overwrite an element/s from a matrix? Explain with example.
Omitting elements: Access the elements you want to omit and assign them a special value like NA
(missing value) or another value that signifies omission in your context.

For example, to omit the element in the second row and third column:
mat <- matrix(1:9, nrow = 3)
mat[2, 3] <- NA
mat
1 4 7
2 5 NA
3 6 9
Overwriting elements: Directly assign new values to specific elements using their indices. This
overwrites the existing values at those positions.
Eg: mat <- matrix(1:9, nrow = 3)
mat[1, 1] <- 99
mat
99 4 7
2 5 8
3 6 9

8. Explain any 3 matrix operations using R commands with example. (6)


(i) Matrix Transpose: For any matrix A, its transposeis obtained by writing either its columns as
rows or its rows as columns. In R, the transpose of a matrix is found with the function t().
Eg: A <- rbind(c(2,5,2),c(6,1,4))
A
2 5 2
6 1 4
t(A)
2 6
5 1
2 4

(ii) Scalar Multiple of a Matrix : Multiplication of any matrix A by a scalar value a results in a
matrix in which every individual element is multiplied by a.
Eg : A <- cbind(c(1,2),c(3,4))
a <- 2
a*A
2 6
4 8

(iii) Addition and Subtraction : Addition or subtraction of two matrices of equal size is also
performed in an element-wise fashion.
Eg : A <- cbind(c(1,2),c(3,4))
B <- cbind(c(1,1),c(1,1))
A+B
2 4
3 5

9. How do you create arrays in R? Explain with suitable example.


In R, you can create arrays using the array() function. An array in R is a multi-dimensional object
that can hold elements of the same data type.
Syntax: array(data, dim)

data: A vector of values to be stored in the array.


dim: A vector specifying the dimensions of the array (rows, columns, and matrices).
Eg: myArray <- array(1:12, dim = c(3, 4))

It generates a 3x4 array with elements from 1 to 12.

You can access elements of the array using indexing.

Eg: myArray[2]
2
10. Explain any 3 relational and logical operators used in R, with an example.
a. Relational operators:
== : Checks if two values are equal. It returns true if they are equal, otherwise returns false.
Eg: x = 2
y = 5
x == y
FALSE

!= : Checks if two values are not equal. It returns true if they are not equal, otherwise returns
false.
Eg: x != y
TRUE

> : Checks if the left value is greater than the right value. It returns true if the left value is greater
than the right value.
Eg: x > y
FALSE

b. Logical operators:
& : Performs element-wise logical AND. It returns true only if both logicals are true.
Eg: TRUE & TRUE
TRUE

| : Performs element-wise logical OR. It returns is true if at least one of the logicals is true.
Eg: TRUE | TRUE
TRUE

! : Negates the logical values in a vector. It returns the opposite of the logical value it’s used on.
Eg: !TRUE
FALSE

11. Explain any, all and which functions with example, on logical vector.
any(): The any() function returns TRUE if at least one element in a logical vector is TRUE.
A <- c(TRUE, FALSE, FALSE)
any(A)
TRUE

all(): The all() function returns TRUE if all elements in a logical vector are TRUE.
A <- c(TRUE, FALSE, FALSE)
all(A)
FALSE

which(): The which() function returns the indices of elements in a logical vector that are TRUE.
A <- c(TRUE, FALSE, FALSE)
which(A)
1

12. Explain cat and paste functions with necessary arguments in R. Give an example.
cat() : will output the concatenated string to the console, but it won't store the results in a variable.
sep: Separator to use between objects (default is a space).
fill: If TRUE, lines are filled with spaces to a common length.
labels: Character vector of labels to be printed before each object.
append: If TRUE, output is appended to an existing file.
Eg: cat("hey", "there", "everyone")
hey there everyone
paste() : Concatenates strings and vectors of strings, creating a new character vector.
sep: Separator to use between elements (default is a space).
collapse: Character string to use to collapse the resulting vector into a single string.
Eg: A <- paste("hey", "there", "everyone")
A
"hey there everyone"

13. Write a note on escape sequences with example.


An escape sequence lets you enter characters that control the format and spacing of the string,
rather than being interpreted as normal text. They begin with a backslash \.

Eg: cat("Hello \nWorld")


Hello
World

14. Explain substr, sub and gsub functions on strings with an example.
substr() : It extracts the part of the string between two character positions, indicated with numbers
passed as start and stop arguments.
Syntax: substr(x, start, stop)
Eg: text<-"Hello World"
substr(text,start=1,stop=5)
"Hello"

sub() : It is used for pattern replacement in strings. It replaces the first occurrence of a pattern with
a replacement.
Syntax: sub(pattern, replacement, x)
Eg: text <- "apple, banana, apple"
sub(pattern="apple",replacement ="grape",x=text)
"grape, banana, apple"

gsub() : The gsub() function is similar to sub(), but it replaces all occurrences of a pattern.
Syntax: gsub(pattern, replacement, x)
Eg: text <- "apple, banana, apple"
gsub(pattern="apple",replacement ="grape",x=text)
"grape, banana, grape"

15. What is factor? How do you define and order levels in a factor?
Factors are the data objects which are used to categorize the data and store it as levels. They can
store both strings and integers. They are useful in the columns which have a limited number of
unique values like "Male, "Female" and True, False etc.
To define and order levels in a factor, you can use factor() function along with level() to specify the
order of levels.
Eg: # Define a factor with levels in a specific order
gender <- factor(c("Male", "Female", "Male", "Male", "Female"), levels =
c("Female", "Male"))
# To reorder levels
gender <- factor(gender, levels = c("Male", "Female"))

16. Explain cut function on factors with an example.


The cut() function in R is used to categorize and split a continuous variable into intervals or bins. It
is often used with factors to create categorical variables.
Syntax : cut(x, breaks, labels)
x: The numerical vector to be cut into intervals.
breaks: A vector of breakpoints defining the intervals.
labels: Optional labels for the resulting factor levels (defaults to interval ranges).

Eg: ages <- c(25, 40, 35, 60, 30, 45, 50, 22, 32, 55)
age_groups <- cut(ages, breaks = c(0, 25, 35, 45, 60),
labels = c("Young", "Mid", "Mid-Old", "Old"))

In this example, cut() divides the ages vector into four age groups based on the specified breaks and
assigns labels to each group.

17. What do you mean by member reference in lists? Explain with an example. (4)
Member reference in lists refers to accessing or retrieving elements or values within a list by
specifying the names or indexes of the elements. Lists in R are collections of elements, and each
element can be referenced using the $ operator or the double square brackets [[]].
Eg: my_list <- list(name = "John", age = 30, scores = c(85, 90, 78))

# Using $ operator to access elements


my_list $ name
“John”

# Using double square brackets to access elements


my_list[["age"]]
30

18. What is data frame? Create a data frame as shown in the given table and write R
commands.
a) To extract the third, fourth, and fifth elements of the third column
b) To extract the elements of age column using dollar operator
Person Age Sex
Peter 42 M
Lois 40 F
Meg 17 F
Chris 14 M
Stewie 1 M
Data Frames are data displayed in a format as a table. Data Frames can have different types of data
inside it. While the first column can be character, the second and third can be numeric or logical.
However, each column should have the same type of data.

The following R command will create the data frame shown above:
mydata <- data.frame(person=c("Peter","Lois","Meg","Chris","Stewie"),
age=c(42,40,17,14,1),
sex=factor(c("M","F","F","M","M")))
(a) mydata[3:5,3]
F M M

(b) mydata$age
42 40 17 14 1

19. How do you add data columns and combine data frames? Explain with example.
You can add data columns to a data frame using the $ operator or by using functions like cbind().
Assign a new vector to a new column name within the data frame. Ensure the new vector has the
same length as the existing rows.
Eg : df1 <- data.frame(name = c("Alice", "Bob", "Charlie"), age = c(25, 30, 22))
df1$score<-c(85,90,78)
df1

To combine data frames, you can use functions like rbind() or merge().
Eg: df1 <- data.frame(name = c("Alice", "Bob", "Charlie"), age = c(25, 30, 22))
df2 <- data.frame(name = c("Jake"), age = c(21))
df3<-rbind(df1,df2)
df3

20. Write a note on special values used in R with an example for each.
NA : Stands for "Not Available" and is used to represent missing or undefined values.
Example: x <- c(1, 2, NA, 4)

NaN : Stands for "Not a Number" and is used to represent undefined or unrepresentable real
numbers, often arising from calculations.
Example: sqrt(-1)

Inf and -Inf : Represents positive and negative infinity, respectively.


Example: 1/0 and -1/0

NULL : Represents the absence of a value or an empty object.


Example: a <- NULL
21. Explain Is-Dot Object-Checking Functions and As-Dot Coercion Functions with an
example.
Is-Dot Object-Checking Functions : These functions are used to check whether an object belongs
to a specific class or type. They return a logical value (TRUE or FALSE). Some functions are
is.numeric(), is.character(), is.factor(), is.logical().
Eg: my_vector <- c(1, 2, 3, 4, 5)
is.numeric(my_vector)
TRUE

In this example, is.numeric() checks if the object my_vector is of numeric type, and it returns
TRUE because the vector contains numeric values.

As-Dot Coercion Functions : These functions are used for type coercion, converting an object
from one type to another. They typically have the form as.*(), where * represents the target class or
type. Examples include as.character(), as.numeric(), as.logical(), etc.
Eg: char_vector <- c("1", "2", "3", "4", "5")
as.numeric(char_vector)
1 2 3 4 5

In this example, as.numeric() coerces the character vector char_vector to a numeric vector and
returns numeric equivalents of the character values.

22. List and explain graphical parameters used in plot function in R with example (any 4)
The plot() function in R allows you to specify various graphical parameters to customize the
appearance of the plot. Here are four graphical parameters:
(i) type : specifies the type of plot to be drawn. It can take values such as "p" (points), "l" (lines),
"b" (both points and lines), "o" (overplotted), and more.
(ii) main: Sets the title of the plot.
(iii) xlab: Sets the label for the x-axis.
(iv) ylab: Sets the label for the y-axis.
Eg: x <- 1:10
y <- x^2
plot(x, y,type=“b, main="Quadratic Function", xlab="X-axis",ylab="Y-axis")

23. How do you add Points, Lines, and Text to an Existing Plot? Explain with example.
Adding points : To add points to an existing plot, you can use the points() function.
Adding lines: To add lines to an existing plot, you can use the lines() function.
Adding texts: To add text to an existing plot, you can use the text() function.
Eg: x <- 1:5
y <- x^2
plot(x, y, main = "Plot")
# Add points
a<-c(3,6,8)
b<-a^2
points(a, b, col = "red", pch = 2)
#Add lines
lines(c(2,8),c(4,64),col="blue",lty=2)
# Add text
text(5, 25, labels = "Text Example", pos = 3)

24. How do you set appearance constants and aesthetic mapping with geoms? Explain with
example.
Setting Appearance Constants:
It Apply a consistent visual style to all elements within a geom. It is set using arguments within the
geom function itself. Common arguments:
color: Sets the color of elements.
fill: Sets the fill color for shapes like bars and polygons.
size: Controls the size of elements (e.g., points, lines).
alpha: Adjusts the transparency of elements.
linetype: Sets the line type (solid, dashed, etc.).
Eg :
ggplot(data = my_data) +
geom_point(aes(x=x, y=y), color="blue", size=3) + # All points are blue, size 3
geom_line(aes(x=x, y=y), color="red", linetype="dashed") # Red dashed line

Aesthetic Mapping:
It dynamically links data variables to visual properties of geoms. It uses the aes() function within
the geom call. Common aesthetics:
x: Maps a variable to the x-axis position.
y: Maps a variable to the y-axis position.
color: Maps a variable to color.
fill: Maps a variable to fill color.
size: Maps a variable to size.
shape: Maps a variable to point shape.

Eg:
ggplot(data = my_data) +
geom_point(aes(x=weight, y=height, color=species)) + # Colors points by species
geom_bar(aes(x=species, fill=gender)) # Fills bars based on gender

You might also like