R Prog Pract3
R Prog Pract3
Vectors are a fundamental data structure in R. They are created using the c() function.
Q.1 Create a vector in R containing the numbers 1, 2, 3, 4, and 5. Perform the following
tasks:
CODE:
# Creating a vector
# Accessing elements
print(vector_plus_two)
# Vector length
Output
[1] 3 4 5 6 7
2. Matrices
Matrices in R are created using the matrix() function. They are two-dimensional.
Q.2 Create a 3x3 matrix in R with elements from 1 to 9 filled by columns. Perform the
following tasks:
1. Access and print the element at the second row and third column.
2. Add 1 to each element in the matrix and display the updated matrix.
CODE:
# Creating a matrix
# Accessing an element
print(matrix_plus_one)
Output
[1,] 2 3 4
[2,] 5 6 7
[3,] 8 9 10
3. Arrays
Arrays can have more than two dimensions and are created using the array() function.
Q.3 Create a 2x3x2 array in R with elements from 1 to 12. Perform the following tasks:
CODE:
# Accessing an element
print(array_plus_ten)
Output
[1,] 11 12 13
[2,] 14 15 16
[1,] 17 18 19
[2,] 20 21 22
4. Lists
Lists in R can contain elements of different types and are created using the list()
function.
Q.4) Create a list in R containing the following elements: a numeric vector with values 1, 2,
3, a character string "Data", and a logical value TRUE. Perform the following tasks:
CODE:
# Creating a list
print(my_list)
print(my_list)
Output
$numbers
[1] 1 2 3
$text
[1] "Data"
$flag
[1] TRUE
$NewElement
[1] 100
$text
[1] "Data"
$flag
[1] TRUE
$NewElement
[1] 100
5. Data Frames
Q.5) Create a data frame in R with the following columns: StudentName (containing "Alice",
"Bob", "Charlie"),Age (containing 25, 30, 35), and City (containing "New York", "Los
Angeles", "Chicago"). Perform the following tasks:
Data frames are used to store tabular data and are created using the data.frame()
function.
CODE:
df <- data.frame(
print("Data Frame:")
print(df)
# Accessing a column
print("Ages of people:")
print(df$Age)
print(df)
Output
3 Charlie 35 Chicago
[1] 25 30 35
6. Functions
Functions in R are created using the function keyword. They help encapsulate code
into reusable blocks
1. Use multiply_numbers to find the product of 4 and 7 and print the result.
2. Use is_even to check if the number 10 is even and print the result.
CODE:
return(x * y)
return(number %% 2 == 0)
Output: