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

R Programming Basics and Data Structures

The document provides an overview of statistical computing and R programming, covering topics such as data types, vectors, matrices, and basic plotting. It includes practical examples and code snippets for various operations in R, such as creating vectors, sorting, and using functions like cbind and rbind. Additionally, it discusses the differences between base R graphics and ggplot2 for plotting, along with examples for each.
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)
5 views10 pages

R Programming Basics and Data Structures

The document provides an overview of statistical computing and R programming, covering topics such as data types, vectors, matrices, and basic plotting. It includes practical examples and code snippets for various operations in R, such as creating vectors, sorting, and using functions like cbind and rbind. Additionally, it discusses the differences between base R graphics and ggplot2 for plotting, along with examples for each.
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

Statistical Computing and R Programming

Unit-I

Unit I:

• Introduction of the language,


• numeric, arithmetic, assignment,and vectors,
• Matrices and Arrays, Non-numeric Values,
• Lists and Data Frames, Special Values,
• Classes, and
• Coercion,
• Basic Plotting.

2-mark questions

1. What are the two ways of assignment operators in R? Give an example.

Ans: In R, there are two main types of assignment operators used to assign values
to variables:1. Leftward Assignment (<-): This is the most commonly used
assignment operator in R.

Example: x <- 10 #This assigns the value 10 to the variable x.

2. Equal Sign Assignment (=) : This is also used for assignment, especially within
functions or when writing short code. Example: y = 20 #This assigns the
value 20 to the variable y.

3. Bonus (Less Common): Rightward Assignment (->): Although not among the
"two main" types, it's worth noting that you can also do: Example: 30 -> z #This
assigns 30 to z, but it's rarely used in practice.

2. What is vector? Give an example to create a vector?


Ans: A vector in R is: A sequence of data elements of the same type. Created using
the c() function (short for combine or concatenate).
Example: Creating Vectors in R
1. Numeric Vector
numbers <- c(10, 20, 30, 40)
print(numbers)

2. Character Vector
names <- c("John", "Sam", "Rohan")
print(names)
3. Logical Vector
flags <- c(TRUE, FALSE, TRUE, TRUE)
print(flags)

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


Ans:
# Create a numeric vector
numbers <- c(5, 10, 15, 20, 25)
# Find the length of the vector

vector_length <- length(numbers)


# Print the result
print(vector_length)

4. How do you sort a vector in descending order? Give an example

Ans: Syntax: sort(vector_name, decreasing = TRUE)


# Create a numeric vector
numbers <- c(10, 5, 25, 15)
# Sort the vector in descending order
sorted_desc <- sort(numbers, decreasing = TRUE)
# Print the sorted vector
print(sorted_desc) 1:10
seq(from=1,to=10,by=2)

5. Create and store a sequence of values from 5 to −11 that progresses in steps of
0.3

Ans: # Create the sequence


sequence <- seq(from = 5, to = -11, by = -0.3)
# Print the sequence
print(sequence)

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: myvect <- c(5, -3, 4, 4, 4, 8, 10, 40221, -8, 1)


# Remove the last element
myvect <- myvect[-length(myvect)]
# Print the updated vector
print(myvect)

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

Ans: In R, negative indexing is used to exclude specific elements from a vector.


It tells R to remove the specified positions instead of selecting them.
myvect <- c(10, 20, 30, 40, 50)
# Exclude the 3rd element

newvect <- myvect[-3]


print(newvect)

8. If baz <- c(1,-1,0.5,-0.5) and qux <- 3, find the value of baz+quax.

Ans: 'quax': Error: object 'quax' not found


> qux <- 3
> baz + qux
[1] 4.0 2.0 3.5 2.5

9. What is the use of cbind and rbind functions in Matrix? Give an example

Ans:cbind : It joins vectors/matrices side-by-side (adds as new columns).


a <- c(1, 2, 3)
b <- c(4, 5, 6)
result <- cbind(a, b)
print(result)

rbind: It joins vectors/matrices top-to-bottom (adds as new rows).


a <- c(1, 2, 3)
b <- c(4, 5, 6)
result <- rbind(a, b)
print(result)

[Link] do you find the dimension of the matrix? Give an example

Ans: mat <- matrix(1:12, nrow = 3, ncol = 4)


dimensions <- dim(mat)
print(dimensions)

[Link] 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: 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)
print(mat)

Ans: Use Case Description


1. diag(n) Creates an identity matrix of size n × n (1s on the diagonal, 0
elsewhere)
2. diag(x) where x is a vector Creates a diagonal matrix with elements of x on the
diagonal and 0 elsewhere
3. diag(m) where m is a matrix Extracts the diagonal elements of the matrix m
identity_matrix <- diag(3)
print(identity_matrix)
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1

v <- c(4, 5, 6)
diag_matrix <- diag(v)
print(diag_matrix)
[,1] [,2] [,3]
[1,] 4 0 0
[2,] 0 5 0
[3,] 0 0 6

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


diag_elements <- diag(m)
print(diag_elements)
[1] 1 5 9

[Link] proper code to replace the third column of matrix B with the values in the
third row of B.
Ans:
# Example matrix B (you can replace this with your actual matrix)
B <- matrix(1:16, nrow = 4, byrow = TRUE)
print("Original matrix B:")
print(B)
B[,3]=B[3,]
# Replace the third column with the third row
B[, 3] <- B[3, ]
print("Matrix B after replacing the 3rd column with the 3rd row:")
print(B)
[Link] an example to find transpose and inverse of a matrix using R command?
Ans:
# Create a square matrix
A <- matrix(c(4, 7, 2, 6), nrow = 2, byrow = TRUE)
print("Matrix A:")
print(A)

# Transpose of matrix A
A_transpose <- t(A)
print("Transpose of A:")
print(A_transpose)

# Inverse of matrix A
A_inverse <- solve(A)
print("Inverse of A:")
print(A_inverse)

[Link] is the difference between & and && in R? Give an example.


Ans:
& Element-wise logical AND Compares each element of two logical
vectors and returns a logical vector
&& Short-circuit logical AND Compares only the first element of two
logical vectors and returns a single TRUE or FALSE
x <- c(TRUE, FALSE, TRUE)
y <- c(TRUE, TRUE, FALSE)

# Using &
result_and <- x & y
print(result_and)
# Output: TRUE FALSE FALSE (element-wise AND)

# Using &&
result_short <- x && y
print(result_short)
# Output: TRUE (only compares the first elements: TRUE && TRUE)

[Link] 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[bar <= 6 & bar != 4]
print(result)

[Link] do you count the number of individual characters in a string? Give an


example.
Ans: nchar(string)
nchar() counts all characters in the string, including spaces and punctuation.
my_string <- "Hello, world!"
char_count <- nchar(my_string)
print(char_count)

[Link] is levels function in R? Give an example


Ans: The levels() function is used to get or set the levels of a factor.
Factors are categorical variables that have fixed possible values called levels.
levels(x) returns the vector of levels of the factor x.
You can also use levels(x) <- new_levels to change the levels.
[Link] is list in R? Give an example.
Ans: In R, a list is a data structure that can hold elements of different types,
including vectors, numbers, strings, other lists, or even functions. Unlike vectors,
where all elements must be of the same type, lists are heterogeneous.
Definition: A list in R is an ordered collection of elements, and each element can
be of any type or structure. Example:
my_list <- list( name = "Alice", age = 30, scores = c(85, 90, 88), passed =
TRUE )
Here’s what this list contains:
name: a character string
age: a numeric value
scores: a numeric vector
passed: a logical value
Accessing List Elements:
By name: my_list$name # "Alice"
By index: my_list[[2]] # 30 #If you want to get a sublist (not just the
value):

my_list[2] # returns a list containing the second element

[Link] is list slicing in lists? Give an example.


Ans: List slicing in R means extracting specific elements (or a subset) from a list
based on their index positions or names.
Unlike vectors, where slicing returns elements directly, slicing a list can return:
The element values (if using [[ ]])
A sublist (if using [ ])
Types of Slicing in R Lists:
1. Slicing to Get a Sublist : Use single square brackets [ ].
my_list <- list("apple", "banana", "cherry", 42, TRUE) # Slice to get the first
three elements as a sublist
sublist <- my_list[1:3]
print(sublist)
Output:
[[1]]
[1] "apple"
[[2]]
[1] "banana"
[[3]]
[1] "cherry"
The result is still a list.
2. Slicing to Get Individual Elements : Use double square brackets [[ ]] to extract
the actual element (not as a list).
# Get the second element
second_element <- my_list[[2]]
print(second_element)
Output:
[1] "banana"
This gives the actual value, not a list.
3. Slicing by Name

If your list has named elements:

named_list <- list(name = "Alice", age = 25, score = 90)

# Get by name
named_list["age"] # returns a sublist
named_list[["age"]] # returns just the value

[Link] do you name list contents? Give an example.


Ans:
1. Naming List Contents at Creation
Use the list() function with named arguments:

person <- list(name = "Alice", age = 30, passed = TRUE) #Now the list
has named elements:
print(person)

Output:
$name
[1] "Alice"

$age
[1] 30

$passed
[1] TRUE

2. Naming List Contents After Creation : If you create a list without names, you
can add them later:

my_list <- list("Alice", 30, TRUE)


# Add names
names(my_list) <- c("name", "age", "passed")
print(my_list)

Output:
$name
[1] "Alice"
$age
[1] 30

$passed
[1] TRUE

Accessing Named Elements:


By name: my_list$name # "Alice"
my_list[["age"]] # 30

By index: my_list[[2]] # 30

[Link] is the purpose of attributes and class functions? Give an example.


Ans: These functions are used to inspect, modify, and define metadata and object
types in R.

1. attributes() Function : attributes() is used to view or set metadata (like names,


dimensions, row names, etc.) of an R object.
Example: x <- 1:5
attributes(x) # No attributes yet

Now let's add an attribute:


attr(x, "description") <- "This is a numeric vector"
attributes(x)

Output: $description
[1] "This is a numeric vector"

2. class() Function: class() is used to check or assign the class (i.e., the type) of an
object. This determines how functions like print(), summary(), and plot() behave
with that object.
Example: my_date <- [Link]("2023-01-01")
class(my_date)
Output:
[1] "Date"

You can even assign a custom class:


person <- list(name = "Alice", age = 30)
class(person) <- "person"
class(person) # Output: "person"

Now you could create methods specifically for objects of class "person".
[Link] is the difference between ggplot2 and base R graphics create plots? Give
an example.
Ans: In R, there are two main systems for creating plots:

Feature Base R Graphics ggplot2 (Grammar of Graphics)


Style Quick, functional Layered, declarative
Syntax Function-based Grammar-based (builds
layer by layer)
Customization Requires manual tweaking Highly
customizable with consistent syntax
Extensibility Limited Highly extensible
(themes, facets, etc.)
Output Consistency Less consistent across plots Consistent
aesthetics and structure

Feature Base R Graphics ggplot2 (Grammar of Graphics)


Style Quick, functional Layered, declarative
Syntax Function-based Grammar-based (builds
layer by layer)
Customization Requires manual tweaking Highly
customizable with consistent syntax
Extensibility Limited Highly extensible
(themes, facets, etc.)
Output Consistency Less consistent across plots Consistent
aesthetics and structure

1. Base R Plot Example


# Using built-in dataset
x <- mtcars$wt
y <- mtcars$mpg

plot(x, y,
main = "MPG vs Weight",
xlab = "Car Weight",
ylab = "Miles Per Gallon",
col = "blue",
pch = 19)

Base R is good for quick, simple visualizations but becomes verbose for more
complex ones.

2. ggplot2 Plot Example


library(ggplot2)
ggplot(data = mtcars, aes(x = wt, y = mpg)) +
geom_point(color = "blue") +
labs(title = "MPG vs Weight", x = "Car Weight", y = "Miles Per Gallon")

ggplot2 builds the plot layer by layer, making it easy to add elements like trend
lines, themes, or color encoding.

You might also like