How do you slice arrays in R language?
In R language, you can use square brackets [] to slice arrays. Here are some examples:
- Slice the vector.
# 创建一个向量
vec <- c(1, 2, 3, 4, 5)
# 切片操作,提取第2到第4个元素
sub_vec <- vec[2:4]
print(sub_vec)
- Slice the matrix.
# 创建一个3x3的矩阵
mat <- matrix(1:9, nrow=3)
# 切片操作,提取第1行和第2列的元素
sub_mat <- mat[1, 2]
print(sub_mat)
- Perform slicing operation on an array.
# 创建一个3x3x3的数组
arr <- array(1:27, dim=c(3,3,3))
# 切片操作,提取第1个元素的值
sub_arr <- arr[1,1,1]
print(sub_arr)
By using square brackets [] for slicing operations, specific elements or subsets can be easily extracted from an array.