SolvedQB UNIT 1
SolvedQB UNIT 1
2 Marks:
1. What are the two ways of assignment operators in R? Give an example.
Ans: 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?
Ans: 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.
Ans: 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
Ans: To sort a vector in descending order in R, you can use the sort() function with the
decreasing parameter set to TRUE.
For example:
1. vec <- c(5, 2, 8, 1, 3)
2. 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
Ans: 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.
Ans: 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 <- my_vect[-length(my_vect)] removes the last element.
7. Write the purpose of negative indexing in vectors? Give an example.
Negative indexing in vectors is used to delete(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+quax.
Ans: To find the value of baz + qux you can do:
baz <- c(1, -1, 0.5, -0.5)
qux <- 3
result <- baz + qux will add 3 to each element of the baz vector.
9. What is the use of cbind and rbind functions in Matrix? Give an example
Ans: cbind and rbind are functions in R used to combine vectors or matrices into a matrix.
cbind combines objects by columns,
rbind combines objects by rows. For example:
x <- c(1, 2, 3)
y <- c(4, 5, 6)
combined <- cbind(x, y) will create a 3x2 matrix with x and y as columns.
combined <- rbind(x, y) will create a 3x2 matrix with x and y as rows.
10.How do you find the dimension of the matrix? Give an example
Ans: 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) #will return the dimensions as 2 3, indicating 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.
Ans: To construct a 4x2 matrix filled row-wise with the specified values, you can use the
matrix() function in R. Here's how you can create it:
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)
12.What is the use of diag command in R? Give an example.
Ans: 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: diag_matrix <- diag(1:4)
To extract the diagonal elements from a matrix:
mat<-matrix(1:9,nrow=3)
diagonal_elements <- diag(mat)
13.Write proper code to replace the third column of matrix B with the values in the
third row of B.
Ans: 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?
Ans: To find the transpose and inverse of a matrix in R:
mat<-matrix(1:9,nrow=3)
Transpose: t(mat) #where mat is your matrix.
Inverse: solve(mat) #where mat is a square, invertible matrix.
15.What is the difference between & and && in R? Give an example.
Ans: 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.
Ans: bar <- c(8, 8, 4, 4, 5, 1, 5, 6, 6, 8)
result <- bar <= 6 & bar != 4
17.How do you count the number of individual characters in a string? Give an
example.
Ans: To count the number of individual characters in a string in R, you can use the nchar()
function. For example:
text <- "Hello, World!"
char_count <- nchar(text) will return 13.
18.What is levels function in R? Give an example
Ans: 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"))
gender_levels <- levels(gender) #will return a vector of levels: "Female" "Male".
19.What is list in R? Give an example.
list in R is a data structure that can hold a collection of objects of different types. For
example:
my_list <- list(name = "John", age = 30, scores = c(85, 90, 78))
20.What is list slicing in lists? Give an example.
Ans: List slicing can be done using indexing and subsetting. For example:-
my_list <- list("apple", "orange", "banana", "grape", "melon")
23.What is the difference between ggplot2 and base R graphics create plots? Give
an example.
Ans: 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)
4 And 6 marks
1. Explain seq, rep and length functions on vectors with example.
Ans:
seq: The seq() function in R 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.
For example:
sequence <- seq(1, 10, by = 2) # Creates a sequence: 1, 3, 5, 7, 9
rep: The rep() function 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.
For example:
vector <- c(1, 2, 3)
repeated_vector <- rep(vector, times = 3)
# Repeats the vector three times: 1, 2, 3, 1, 2, 3, 1, 2, 3
length: The length() function is used to determine the length of a vector, which is the number
of elements it contains. For example:
my_vector <- c(4, 7, 2, 9, 5)
vector_length <- length(my_vector) # Returns the length of the vector, which is 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.
Ans:
original_vector <- c(-1, 3, -5, 7, -9)
3. How do you extract elements from vectors? Explain it using individual and vector
of indexes with example?
Ans: Individual Indexing: You can extract elements from a vector by specifying the index of
the element you want.
For example:
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. For
example:
indices <- c(2, 4)
selected_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.
Ans: To create a matrix in R, you can use the matrix() function. The necessary attributes are
the data elements, the number of rows, and the number of columns.
Example:
mat <- matrix(data=c(1:12), nrow = 3, ncol = 4, byrow = TRUE)
data: The vector containing the data elements.
nrow: The number of rows in the matrix (3 in this example).
ncol: The number of columns in the matrix (4 in this example).
byrow: If byrow = TRUE, data is filled row-wise; if byrow = FALSE (default), data is filled
column-wise.
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.
Ans:
a. Retrieve third and first rows of A, in that order, and from those rows, second and third column
elements:
A <- matrix(c(1:9), nrow = 3)
rows <- c(3, 1)
cols <- c(2, 3)
result <- A[rows, cols]
b. diagonal_elements <- diag(A)
c. A <- A[, -2]
6. Explain row, column, and diagonal extractions of matrix elements with example.
Ans:
Row extraction: You can extract specific rows from a matrix by specifying the row indices.
For example:
mat <- matrix(1:12, nrow = 3)
row2 <- mat[2, ] # Extracts the second row
Column extraction: You can extract specific columns from a matrix by specifying the column
indices. For example:
mat <- matrix(1:12, nrow = 3)
col3 <- mat[, 3] # Extracts the third column
Diagonal extraction: To extract the diagonal elements of a matrix, you can use the diag()
function. For example:
mat <- matrix(1:9, nrow = 3)
diagonal_elements <- diag(mat) # Extracts the diagonal elements
7. How do you omit and overwrite an element/s from a matrix? Explain with
example.
Ans:
To omit and overwrite elements in a matrix, you can simply assign new values to the elements
you want to modify. For example, to omit the element in the second row and third column and
overwrite an element:
mat <- matrix(1:9, nrow = 3)
mat[2, 3] <- NA # Omit the element
mat[1, 1] <- 99 # Overwrite an element
11.Explain any, all and which functions with example, on logical vector.
Ans: any(): The any() function returns TRUE if at least one element in a logical vector is
TRUE. For example:
logical_vector <- c(TRUE, FALSE, FALSE)
result <- any(logical_vector) # Returns TRUE
all(): The all() function returns TRUE if all elements in a logical vector are TRUE. For example
logical_vector <- c(TRUE, TRUE, TRUE)
result <- all(logical_vector) # Returns TRUE
which(): The which() function returns the indices of elements in a logical vector that are TRUE.
For example:
logical_vector <- c(TRUE, FALSE, TRUE, TRUE, FALSE)
indices <- which(logical_vector) # Returns indices 1, 3, 4
12.Explain cat and paste functions with necessary arguments in R. Give an example.
Ans:
cat: The cat() function in R is used to concatenate and print values together. It prints the values
without any separators by default.
cat("Hello", "World")
# Output: Hello World
paste: The paste() function is used to concatenate strings or other objects with a specified
separator.
result <- paste("Hello", "World", sep = ", ")
# Result: "Hello, World"
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.
# Extracting the third, fourth, and fifth elements of the third column
third_to_fifth_third_column <- df[3, 3:5]
print(third_to_fifth_third_column)
# Extracting the elements of the age column using the dollar operator
age_column <- df$Age
print(age_column)
19.How do you add data columns and combine data frames? Explain with example.
Ans:
You can add data columns to a data frame using the $ operator or by using functions like
cbind(). To combine data frames, you can use functions like rbind() or merge(). Here's an
example:
# Create two data frames
df1 <- data.frame(Name = c("Alice", "Bob", "Charlie"), Age = c(25, 30, 22))
df2 <- data.frame(Score = c(85, 90, 78))
# Add a new column to df1
df1$Score <- df2$Score
# Combine data frames using rbind
combined_df <- rbind(df1, df2)
22.List and explain graphical parameters used in plot function in R with example (any 4)
Ans:
The plot() function in R allows you to specify various graphical parameters to customize the
appearance of
the plot. Here are four graphical parameters:
main: Sets the title of the plot.
xlab: Sets the label for the x-axis.
ylab: Sets the label for the y-axis.
col: Sets the color of the plotted points or lines.
Example:
x <- 1:10
y <- x^2
plot(x, y, main = "QuadraticFunction", xlab = "X-axis", ylab = "Y-axis", col = "blue")
23.How do you add Points, Lines, and Text to an Existing Plot? Explain with example.
Ans:
You can add points, lines, and text to an existing plot using functions like points(), lines(), and
text(). Here's
an example of adding points and text to an existing scatter plot:
x <- 1:5
y <- c(3, 6, 4, 9, 7)
plot(x, y, main = "Scatter Plot")
# Add points
points(x, y, col = "red", pch = 2)
# Add text
text(x, y, labels = y, pos = 3)
24.How do you set appearance constants and aesthetic mapping with geoms? Explain
with example.
Ans: In the context of data visualization using ggplot2, appearance constants and aesthetic
mappings can be set
using various geom_ functions. Appearance constants (such as color, size, and shape) define
how the data elements
will look, and aesthetic mappings define how variables in your data map to visual elements.
Here's an example using
geom_point():
library(ggplot2)
# Create a data frame
df <- data.frame(x = c(1, 2, 3, 4, 5), y = c(3, 6, 4, 9, 7), group = c("A", "B", "A", "B", "A"))
# Create a scatter plot with different colors for each group
ggplot(df, aes(x = x, y = y, color = group)) + geom_point(size = 4, shape = 21)