How can elements be accessed in an array in R language?

In R language, elements in an array can be accessed using square brackets []. Here are some examples:

  1. Accessing elements in a one-dimensional array:
# 创建一个一维数组
my_array <- c(1, 2, 3, 4, 5)

# 访问第一个元素
print(my_array[1])

# 访问最后一个元素
print(my_array[length(my_array)])
  1. Accessing elements in a multi-dimensional array:
# 创建一个二维数组
my_matrix <- matrix(1:9, nrow = 3)

# 访问第一行,第二列的元素
print(my_matrix[1, 2])

# 访问第二行的所有元素
print(my_matrix[2, ])

# 访问所有行的第三列元素
print(my_matrix[, 3])

By using the index within the brackets, you can access elements in the array based on the desired dimension and position.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds