Arrays in R Programming Language

In R, an array is a multi-dimensional collection of elements of the same data type. While arrays are less commonly used in R compared to vectors and lists, they can be useful in certain scenarios, especially when dealing with multi-dimensional data.

# Here we create an array `a` that will hold exactly 5 integers.
# In R, we use the `array()` function to create arrays.
a <- array(0, dim = 5)
print(paste("emp:", paste(a, collapse = " ")))

# We can set a value at an index using the
# array[index] <- value syntax, and get a value with array[index].
a[5] <- 100
print(paste("set:", paste(a, collapse = " ")))
print(paste("get:", a[5]))

# The `length()` function returns the total number of elements in an array.
print(paste("len:", length(a)))

# Use this syntax to declare and initialize an array in one line.
b <- array(c(1, 2, 3, 4, 5), dim = 5)
print(paste("dcl:", paste(b, collapse = " ")))

# In R, we don't have a direct equivalent to Go's `...` for array initialization.
# However, we can achieve similar results by using `c()` to combine elements.
b <- array(c(1, 2, 3, 4, 5))
print(paste("dcl:", paste(b, collapse = " ")))

# R doesn't have a direct equivalent to Go's index-based initialization.
# We can achieve a similar result by creating the array and then assigning values.
b <- array(0, dim = 5)
b[1] <- 100
b[4] <- 400
b[5] <- 500
print(paste("idx:", paste(b, collapse = " ")))

# Array types in R can be multi-dimensional.
# Here's how to create and initialize a 2D array:
twoD <- array(0, dim = c(2, 3))
for (i in 1:2) {
  for (j in 1:3) {
    twoD[i, j] <- i + j - 2  # Subtracting 2 to match Go's 0-based indexing
  }
}
print("2d:")
print(twoD)

# You can create and initialize multi-dimensional arrays at once too.
twoD <- array(c(1, 2, 3, 1, 2, 3), dim = c(2, 3))
print("2d:")
print(twoD)

When you run this R script, you’ll see output similar to this:

[1] "emp: 0 0 0 0 0"
[1] "set: 0 0 0 0 100"
[1] "get: 100"
[1] "len: 5"
[1] "dcl: 1 2 3 4 5"
[1] "dcl: 1 2 3 4 5"
[1] "idx: 100 0 0 400 500"
[1] "2d:"
     [,1] [,2] [,3]
[1,]    0    1    2
[2,]    1    2    3
[1] "2d:"
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1    2    3

Note that arrays in R are printed in a different format compared to Go. For one-dimensional arrays, we use paste() to create a string representation similar to Go’s output. For multi-dimensional arrays, R provides a matrix-like representation.

R’s arrays are more flexible than Go’s in some ways. They can have any number of dimensions, and the array() function allows you to specify the dimensions when creating the array. However, R doesn’t have some of the initialization shortcuts that Go provides, so we have to use different approaches to achieve similar results.