在 R 中创建偶数序列的二维数组
在本文中,我们将讨论如何在 R 编程语言中创建偶数序列的二维数组。
方法 1:使用seq()方法
array() 方法可用于创建具有 >=1 维的数组。此方法返回一个数组,其范围在 dim 属性中指定。对于二维数组,dim 属性包含两个元素的向量,分别表示行数和列数。
Syntax: array(data , dim)
Parameter :
- data – The data to fill into the array
- dim – The dimensions of the matrix in the form of vector
此方法中的数据可以使用 seq() 方法创建,该方法用于在定义的数字范围内生成规则序列。
Syntax: seq(from = 1, to = 1, length.out , by = ((to – from)/(length.out – 1))
Parameter:
- from, to – (Default : 1) The starting and (maximal) end values of the sequence.
- by – Indicator of the number to increment the sequence by.
- length.out – A non-negative integer indicator of the length of the sequence.
在这种方法中, from 属性必须是偶数才能生成偶数整数序列。 length.out 参数将等于二维矩阵的维度乘积。而 by 属性的值为 2,每次将数字增加 2。
例子:
R
# creating integers
mat <- seq(from = 2, length.out = 12, by = 2)
# creating dimensions
dim <- c(4, 3)
arr <- array( mat , dim )
print("Array of even integers sequence:")
print(arr)
R
# specifying where to start the
# even integers from
start_pos <- 20
# specifying dimensions of matrix
nrow <- 3
ncol <- 2
# calculating starting position
end_pos = (nrow * ncol * 2) + start_pos
# creating empty vector
vec <- c()
for (i in start_pos : end_pos-1){
# check if element is divisible by 2
if(!(i%%2)){
# append element to vector
vec <- c(vec, i )
}
}
# creating matrix
mat <- matrix(vec , nrow = 3)
print ("Sequence of even integers in 2-D array")
print (mat)
输出
[1] "Array of even integers sequence:"
[,1] [,2] [,3]
[1,] 2 10 18
[2,] 4 12 20
[3,] 6 14 22
[4,] 8 16 24
方法二:手动使用for循环
开始数据序列的起始位置与二维数组的所需维度一起指定。由于所需元素的总数等于维度的乘积,但这里我们需要出现在交替位置的偶数。因此,元素的总数将相当于维度乘积的两倍。现在,结束位置由下式给出:
ending_position = starting_position + number of elements
开始一个for循环,从起始位置到结束位置1进行迭代,生成这个范围内的元素序列,遇到偶数时,将该数字追加到空列表中。这个向量形成偶数序列,可以输入到基 R 的 matrix() 方法,它创建一个 2D 矩阵。
句法:
matrix (data , nrow = )
时间复杂度可以假设为几乎恒定,直到非常大的维度尺寸。
例子:
电阻
# specifying where to start the
# even integers from
start_pos <- 20
# specifying dimensions of matrix
nrow <- 3
ncol <- 2
# calculating starting position
end_pos = (nrow * ncol * 2) + start_pos
# creating empty vector
vec <- c()
for (i in start_pos : end_pos-1){
# check if element is divisible by 2
if(!(i%%2)){
# append element to vector
vec <- c(vec, i )
}
}
# creating matrix
mat <- matrix(vec , nrow = 3)
print ("Sequence of even integers in 2-D array")
print (mat)
输出
[1] "Sequence of even integers in 2-D array"
[,1] [,2]
[1,] 20 26
[2,] 22 28
[3,] 24 30