w3resource

Creating an Array in R with named dimensions

R Programming: Basic Exercise-17 with Solution

Write a R program to create an array, passing in a vector of values and a vector of dimensions. Also  provide names for each dimension.

Sample Solution :

R Programming Code :

# Create an array with values from 6 to 30
a = array(
  6:30,  # Define the values for the array
  dim = c(4, 3, 2),  # Specify the dimensions of the array: 4 rows, 3 columns, 2 parts
  dimnames = list(  # Provide names for the dimensions
    c("Col1", "Col2", "Col3", "Col4"),  # Names for the columns
    c("Row1", "Row2", "Row3"),  # Names for the rows
    c("Part1", "Part2")  # Names for the parts
  )
)

# Print the content of the array
print(a)

Output:

, , Part1

     Row1 Row2 Row3
Col1    6   10   14
Col2    7   11   15
Col3    8   12   16
Col4    9   13   17

, , Part2

     Row1 Row2 Row3
Col1   18   22   26
Col2   19   23   27
Col3   20   24   28
Col4   21   25   29                         

Explanation:

  • a = array(...): Creates an array and assigns it to the variable a.
  • 6:30: Defines a sequence of integers from 6 to 30 to be used as the array's values.
  • dim = c(4, 3, 2): Specifies the dimensions of the array:
    • 4 rows
    • 3 columns
    • 2 matrices (or "parts")
  • dimnames = list(...): Assigns names to each dimension of the array:
    • c("Col1", "Col2", "Col3", "Col4"): Names for the rows.
    • c("Row1", "Row2", "Row3"): Names for the columns.
    • c("Part1", "Part2"): Names for the matrices (or "parts").
  • print(a): Outputs the array a to the console, showing its contents and dimension names.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to create a 5 × 4 matrix , 3 × 3 matrix with labels and fill the matrix by rows and 2 × 2 matrix with labels and fill the matrix by columns.
Next: Write a R program to create an array with three columns, three rows, and two "tables", taking two vectors as input to the array. Print the array.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/r-programming-exercises/basic/r-programming-basic-exercise-17.php