在 R 中嵌套 for 循环
本文将介绍 R 中嵌套的 for
循环。
R 语言中的 for
循环
for
循环在 R 语言中可用,其启发式与大多数编程语言中的类似。它多次重复给定的代码块。for
循环语法如下。
for (item in set) {}
item
是一个对象,它存储来自 set
的迭代元素。for
循环不返回输出,因此我们需要调用 print
函数在每次迭代时输出 word
值。
vec1 <- c("ace", "spades", "king", "spades", "queen", "spades", "jack",
"spades", "ten", "spades")
for (word in vec1) {
print(word)
}
输出:
[1] "ace"
[1] "spades"
[1] "king"
[1] "spades"
[1] "queen"
[1] "spades"
[1] "jack"
[1] "spades"
[1] "ten"
[1] "spades"
我们还可以实现 for
循环,其中索引作为变量公开。在这种情况下,length
函数用于计算 vec1
向量的大小并从第一个元素迭代到结尾。请注意,1:
符号很重要,它指定了范围的开始。下面的示例代码使用 for
循环创建一个字符串向量,该向量被复制到另一个相同大小的向量。
vec1 <- c("ace", "spades", "king", "spades", "queen", "spades", "jack",
"spades", "ten", "spades")
vec2 <- vector(length = length(vec1))
for (i in 1:length(vec1)) {
vec2[i] <- vec1[i]
}
vec2
输出:
[1] "ace" "spades" "king" "spades" "queen" "spades" "jack" "spades" "ten"
[10] "spades"
使用嵌套的 for
循环遍历 R 中的矩阵元素
嵌套循环可以使用 for
循环结构来实现。这可用于迭代矩阵元素并用随机值初始化它们。请注意,一般表示法与前面的示例相同,只是范围的末尾是使用 nrow
和 ncol
函数计算的。nrow
和 ncol
分别返回数组的行数或列数。
mat1 <- matrix(0, nrow = 5, ncol = 5)
for (i in 1:nrow(mat1)) {
for (j in 1:ncol(mat1)) {
mat1[i, j] <- sample(1:100, 1, replace=TRUE)
}
}
mat1
输出:
[,1] [,2] [,3] [,4] [,5]
[1,] 13 14 13 67 98
[2,] 28 50 23 55 9
[3,] 3 65 99 17 93
[4,] 18 6 20 50 46
[5,] 51 76 33 26 3
尽管如此,嵌套循环结构在前面的示例代码中运行良好。矩阵初始化最好使用直接链接为 matrix
函数的第一个参数的 sample
函数完成,如下面的代码片段所示。
mat2 <- matrix(sample(1:100, 25, replace = TRUE), ncol = 5)
mat2
输出:
[,1] [,2] [,3] [,4] [,5]
[1,] 85 19 26 53 88
[2,] 44 50 66 96 56
[3,] 42 46 37 19 66
[4,] 43 23 13 32 67
[5,] 56 51 21 2 56
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn