在 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