![]() |
The array is the fundamental data structure in R used to store multiple elements of the same data type. In this article, we will explore two different approaches to creating an array in R Programming Language. Creating an array in RBelow are the approaches for creating an array in R.
Creating an array Using array() functionarray(data, dim = NULL, dimnames = NULL)
The below example shows how we can create an array using array() function.
Output: 1-Dimensional Array:
[1] 1 2 3 4 5
Multi-Dimensional Array:
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12 In this approach, we are using the array() function in R to create arrays. We start by creating a 1 dimensional array using the array(1:5) syntax, which contains elements from 1 to 5. Then, we create a multidimensional array using the array(1:12, dim = c(3, 4)), defining its dimensions as 3 rows and 4 columns. Finally, we use cat() for proper spacing and print the arrays with explanatory labels. Creating an array Using matrix() functionmatrix(data, nrow = ..., ncol = ..., byrow = FALSE, dimnames = NULL)
The below example shows how we can create an array using matrix() function
Output: Example 1 - 2x3 Matrix:
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
Example 2 - 3x2 Matrix:
[,1] [,2]
[1,] 7 10
[2,] 8 11
[3,] 9 12
Example 3 - 4x4 Matrix with Repeating Values:
[,1] [,2] [,3] [,4]
[1,] 10 10 10 10
[2,] 10 10 10 10
[3,] 10 10 10 10
[4,] 10 10 10 10
Example 4 - Matrix with Custom Row and Column Names:
Col1 Col2 Col3 Col4
Row1 "a" "b" "c" "d"
Row2 "e" "f" "g" "h"
Row3 "i" "j" "k" "l" In this approach, we are using the matrix() function in R to create arrays. Example 1 creates a 2×3 matrix with values 1 to 6, Example 2 creates a 3×2 matrix with values 7 to 12, and Example 3 creates a 4×4 matrix filled with the value 10. Example 4 demonstrates creating a matrix with custom row and column names, filled with letters from “a” to “l”, arranged in 3 rows and 4 columns. |
Reffered: https://www.geeksforgeeks.org
R Language |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |