0% found this document useful (0 votes)
0 views8 pages

R

This document provides a comprehensive guide on basic operations with vectors and matrices in R. It covers creating vectors, performing arithmetic operations, using vector functions, indexing, logical operations, combining vectors, and generating sequences. Additionally, it includes a function for user-input matrices and demonstrates matrix addition and subtraction, ensuring users understand how to manipulate and operate on these data structures effectively.

Uploaded by

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

R

This document provides a comprehensive guide on basic operations with vectors and matrices in R. It covers creating vectors, performing arithmetic operations, using vector functions, indexing, logical operations, combining vectors, and generating sequences. Additionally, it includes a function for user-input matrices and demonstrates matrix addition and subtraction, ensuring users understand how to manipulate and operate on these data structures effectively.

Uploaded by

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

#Basic operations with vectors in R

# 1. Creating vectors
vector1 <- c(1, 2, 3, 4, 5) # Numeric vector
vector2 <- c("a", "b", "c", "d") # Character vector
vector3 <- c(TRUE, FALSE, TRUE) # Logical vector

# Display vectors
print("Numeric vector:")
print(vector1)
print("Character vector:")
print(vector2)
print("Logical vector:")
print(vector3)

# 2. Vector arithmetic
vector4 <- c(10, 20, 30, 40, 50)
sum_vector <- vector1 + vector4
diff_vector <- vector4 - vector1
prod_vector <- vector1 * vector4
quot_vector <- vector4 / vector1

print("Sum of vectors:")
print(sum_vector)
print("Difference of vectors:")
print(diff_vector)
print("Product of vectors:")
print(prod_vector)
print("Quotient of vectors:")
print(quot_vector)

# 3. Vector functions
mean_vector1 <- mean(vector1)
sum_vector1 <- sum(vector1)
length_vector1 <- length(vector1)

print("Mean of vector1:")
print(mean_vector1)
print("Sum of vector1:")
print(sum_vector1)
print("Length of vector1:")
print(length_vector1)

# 4. Indexing vectors
second_element <- vector1[2]
elements_2_to_4 <- vector1[2:4]

print("Second element of vector1:")


print(second_element)
print("Elements 2 to 4 of vector1:")
print(elements_2_to_4)

# 5. Logical operations on vectors


logical_vector <- vector1 > 3
filtered_vector <- vector1[vector1 > 3]

print("Logical vector where vector1 > 3:")


print(logical_vector)
print("Filtered vector where vector1 > 3:")
print(filtered_vector)

# 6. Combining vectors
combined_vector <- c(vector1, vector4)
print("Combined vector of vector1 and vector4:")
print(combined_vector)

# 7. Repetition and sequences


rep_vector <- rep(1, 10)
seq_vector <- seq(1, 10, by=2)

print("Repetition vector:")
print(rep_vector)
print("Sequence vector:")
print(seq_vector)

Explanation:

1. Creating vectors: This shows how to create numeric, character, and logical vectors using
the c() function.
2. Vector arithmetic: Demonstrates element-wise addition, subtraction, multiplication, and
division.
3. Vector functions: Uses functions like mean(), sum(), and length() to get summary
statistics.
4. Indexing vectors: Accesses elements of a vector using indices.
5. Logical operations on vectors: Creates a logical vector based on a condition and filters
the vector.
6. Combining vectors: Combines two vectors using the c() function.
7. Repetition and sequences: Creates vectors using rep() and seq() functions.

This script provides a comprehensive introduction to working with vectors in R.

4o
AIM
ChatGPT

The aim of this R script is to introduce and demonstrate the fundamental concepts and operations
associated with vectors in R. By running this script, users will learn how to:

1. Create different types of vectors (numeric, character, and logical).


2. Perform basic arithmetic operations on vectors (addition, subtraction, multiplication,
and division).
3. Utilize common vector functions to compute summary statistics (mean, sum, length).
4. Index and subset vectors to access specific elements or ranges of elements.
5. Apply logical operations on vectors to create logical vectors and filter data based on
conditions.
6. Combine vectors to form new vectors.
7. Generate vectors using repetition and sequences.

Overall, the script serves as an educational tool to help users understand the core concepts of
vectors in R and how to work with them effectively.

4o
ALGLORITHM INPUT OUTPUT RESULT
ChatGPT

Sure! Let's break down the script into an algorithm, including the inputs, outputs, and expected
results.

Algorithm

1. Start
2. Create Vectors
o Input: Define numeric, character, and logical vectors.
o Output: Display the created vectors.
3. Perform Vector Arithmetic
o Input: Two numeric vectors.
o Process: Calculate sum, difference, product, and quotient of the vectors.
o Output: Display results of arithmetic operations.
4. Use Vector Functions
o Input: A numeric vector.
o Process: Calculate mean, sum, and length of the vector.
o Output: Display the results of these functions.
5. Index Vectors
o Input: A numeric vector.
o Process: Access specific elements and ranges of elements.
o Output: Display the accessed elements.
6. Apply Logical Operations
o Input: A numeric vector.
o Process: Create a logical vector based on a condition, and filter the original vector
using this logical vector.
o Output: Display the logical vector and the filtered vector.
7. Combine Vectors
o Input: Two numeric vectors.
o Process: Combine them into a single vector.
o Output: Display the combined vector.
8. Generate Vectors using Repetition and Sequences
o Input: Values to generate repetition and sequence vectors.
o Process: Create repetition and sequence vectors.
o Output: Display the repetition and sequence vectors.
9. End

Input

1. Vectors to be created:
o Numeric vector: c(1, 2, 3, 4, 5)

o Character vector: c("a", "b", "c", "d")


o Logical vector: c(TRUE, FALSE, TRUE)
2. Vectors for arithmetic operations:
o vector1 <- c(1, 2, 3, 4, 5)
o vector4 <- c(10, 20, 30, 40, 50)

3. Values for repetition and sequences:


o rep(1, 10)
o seq(1, 10, by=2)

Output

1. Created Vectors:
o Numeric vector: [1, 2, 3, 4, 5]

o Character vector: ["a", "b", "c", "d"]


o Logical vector: [TRUE, FALSE, TRUE]
2. Arithmetic Operations Results:
o Sum: [11, 22, 33, 44, 55]
o Difference: [9, 18, 27, 36, 45]
o Product: [10, 40, 90, 160, 250]
o Quotient: [10, 10, 10, 10, 10]
3. Vector Functions Results:
o Mean: 3
o Sum: 15
o Length: 5
4. Indexed Elements:
o Second element: 2
o Elements 2 to 4: [2, 3, 4]
5. Logical Operations Results:
o Logical vector: [FALSE, FALSE, FALSE, TRUE, TRUE]
o Filtered vector: [4, 5]
6. Combined Vector:
o Combined vector: [1, 2, 3, 4, 5, 10, 20, 30, 40, 50]
7. Repetition and Sequence Vectors:
o Repetition vector: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
o Sequence vector: [1, 3, 5, 7, 9]

Result

By following this script, users will understand how to create and manipulate vectors in R,
perform basic arithmetic and logical operations, access specific elements, and generate vectors
using repetition and sequences. This foundational knowledge will enable users to handle more
complex data structures and operations in R effectively.

# Aim: To perform matrix addition and subtraction based on user inputs

# Function to take matrix input from the user


get_matrix_input <- function(matrix_number) {
nrows <- as.integer(readline(prompt=paste("Enter the number of rows for
matrix", matrix_number, ": ")))
ncols <- as.integer(readline(prompt=paste("Enter the number of columns for
matrix", matrix_number, ": ")))
cat(paste("Enter the elements of matrix", matrix_number, "row-wise:\n"))
elements <- as.numeric(unlist(strsplit(readline(), " ")))

if (length(elements) != nrows * ncols) {


stop("The number of elements provided does not match the specified
dimensions.")
}

matrix(elements, nrow=nrows, ncol=ncols, byrow=TRUE)


}

# Get matrix inputs from the user


matrix1 <- get_matrix_input(1)
matrix2 <- get_matrix_input(2)

# Check if the dimensions of the matrices match


if (!all(dim(matrix1) == dim(matrix2))) {
stop("Matrices dimensions do not match.")
}

# Perform matrix addition


matrix_addition <- matrix1 + matrix2

# Perform matrix subtraction


matrix_subtraction <- matrix1 - matrix2

# Display results
cat("Matrix 1:\n")
print(matrix1)
cat("Matrix 2:\n")
print(matrix2)
cat("Matrix Addition (Matrix 1 + Matrix 2):\n")
print(matrix_addition)
cat("Matrix Subtraction (Matrix 1 - Matrix 2):\n")
print(matrix_subtraction)

Example Input and Output

Input
 Matrix 1:
o Number of rows: 2

o Number of columns: 2
o Elements: 1 2 3 4
 Matrix 2:
o Number of rows: 2
o Number of columns: 2
o Elements: 5 6 7 8
Output
 Matrix 1:

1 2
3 4
 Matrix 2:

5 6
7 8
 Matrix Addition (Matrix 1 + Matrix 2):

6 8
10 12
 Matrix Subtraction (Matrix 1 - Matrix 2):

diff

-4 -4
-4 -4

Algorithm

1. Start
2. Define a function to get matrix input from the user:
o Prompt for the number of rows.
o Prompt for the number of columns.
o Prompt for the matrix elements row-wise.
o Validate the number of elements against the specified dimensions.
o Return the constructed matrix.
3. Get matrix inputs from the user:
o Call the input function to get the first matrix.
o Call the input function to get the second matrix.
4. Check if the dimensions of the two matrices match:
o If dimensions do not match, display an error message and stop execution.
5. Perform matrix addition:
o Add the two matrices element-wise.
6. Perform matrix subtraction:
o Subtract the second matrix from the first matrix element-wise.
7. Display the results:
o Print the original matrices.
o Print the result of the matrix addition.
o Print the result of the matrix subtraction.
8. End

Result

By running this script, users will be able to perform matrix addition and subtraction with
matrices they input, thereby understanding how to handle matrix operations in R.

You might also like