0% found this document useful (0 votes)
3 views2 pages

Array

Array

Uploaded by

rajkumaramirtha3
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)
3 views2 pages

Array

Array

Uploaded by

rajkumaramirtha3
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/ 2

Powered by AI

Copilot

Certainly! Let’s explore arrays and matrices in R programming with an example:

1. Arrays:

An array is a data structure that can store data in more than two dimensions.
Unlike vectors (uni-dimensional arrays) and matrices (two-dimensional arrays), arrays can have
more than two dimensions.
To create an array in R, we use the array() function.
The syntax for creating an array is: array(vector, dim = c(nrow, ncol, nmat)).
vector: Data items of the same type.
nrow: Number of rows.
ncol: Number of columns.
nmat: Number of matrices (product of nrow and ncol).
Example:
# Create a 2x3x2 array
array1 <- array(c(1:12), dim = c(2, 3, 2))
print(array1)

Output:
, , 1
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6

, , 2
[,1] [,2] [,3]
[1,] 7 9 11
[2,] 8 10 12

2. Accessing Array Elements:

Use the vector index operator [ ] to access specific elements of an array.


Syntax: array[n1, n2, mat_level]
n1: Row position.
n2: Column position.
mat_level: Matrix level.
Example:
# Access element at 1st row, 3rd column of 2nd matrix
cat("Desired Element:", array1[1, 3, 2])

Output:
Desired Element: 11

3. Accessing Entire Rows or Columns:

Use [c(n), , mat_level] to access the entire nth row.


Use [ , c(n), mat_level] to access the entire nth column.
Examples:
# Access 2nd column elements of 1st matrix
cat("2nd Column Elements of 1st matrix:", array1[, c(2), 1])

# Access 1st row of 2nd matrix


cat("1st Row Elements of 2nd Matrix:", array1[c(1), , 2])

Output:
2nd Column Elements of 1st matrix: 3 4
1st Row Elements of 2nd Matrix: 7 9 11
Arrays are versatile for handling multi-dimensional data in R. If you have more questions or need further
examples, feel free to ask! 😊

You might also like