Thursday, 12 October 2023

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

 Slip26

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

 

 

Vector of values

values <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)

 

# Vector of dimensions

dims <- c(3, 3)  # A 3x3 array

 

# Names for each dimension

dimnames_list <- list(

  rownames = c("Row1", "Row2", "Row3"),

  colnames = c("Col1", "Col2", "Col3")

)

 

# Create the array

my_array <- array(values, dim = dims, dimnames = dimnames_list)

 

# Print the array

print(my_array)

 

Output

> values <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)

>

> # Vector of dimensions

> dims <- c(3, 3)  # A 3x3 array

>

> # Names for each dimension

> dimnames_list <- list(

+   rownames = c("Row1", "Row2", "Row3"),

+   colnames = c("Col1", "Col2", "Col3")

+ )

>

> # Create the array

> my_array <- array(values, dim = dims, dimnames = dimnames_list)

>

> # Print the array

> print(my_array)

        colnames

rownames Col1 Col2 Col3

    Row1    1    4    7

    Row2    2    5    8