R中的For循环,附带列表和矩阵的示例
当我们需要迭代一个元素列表或数字范围时,for循环非常有用。循环可用于迭代列表、数据框、向量、矩阵或任何其他对象。大括号和方括号是必需的。
在本教程中,我们将学习,
For 循环语法和示例
For (i in vector) { Exp }
此处,
R 会遍历向量中的所有变量,并执行 exp 中写入的计算。

让我们看几个例子。
R 中 For 循环示例 1:我们遍历向量的所有元素并打印当前值。
# Create fruit vector fruit <- c('Apple', 'Orange', 'Passion fruit', 'Banana') # Create the for statement for ( i in fruit){ print(i) }
输出
## [1] "Apple" ## [1] "Orange" ## [1] "Passion fruit" ## [1] "Banana"
R 中 For 循环示例 2:通过使用 x 在 1 到 4 之间的多项式创建一个非线性函数,并将其存储在列表中
# Create an empty list list <- c() # Create a for statement to populate the list for (i in seq(1, 4, by=1)) { list[[i]] <- i*i } print(list)
输出
## [1] 1 4 9 16
对于机器学习任务,for 循环非常有价值。在训练了模型之后,我们需要对模型进行正则化以避免过拟合。正则化是一项非常繁琐的任务,因为我们需要找到最小化损失函数的值。为了帮助我们检测这些值,我们可以使用 for 循环迭代一系列值并定义最佳候选。
For 循环遍历列表
遍历列表与遍历向量一样简单方便。让我们看一个例子
# Create a list with three vectors fruit <- list(Basket = c('Apple', 'Orange', 'Passion fruit', 'Banana'), Money = c(10, 12, 15), purchase = FALSE) for (p in fruit) { print(p) }
输出
## [1] "Apple" "Orange" "Passion fruit" "Banana" ## [1] 10 12 15 ## [1] FALSE
For 循环遍历矩阵
矩阵有 2 个维度:行和列。要迭代矩阵,我们需要定义两个 for 循环,一个用于行,另一个用于列。
# Create a matrix mat <- matrix(data = seq(10, 20, by=1), nrow = 6, ncol =2) # Create the loop with r and c to iterate over the matrix for (r in 1:nrow(mat)) for (c in 1:ncol(mat)) print(paste("Row", r, "and column",c, "have values of", mat[r,c]))
输出
## [1] "Row 1 and column 1 have values of 10" ## [1] "Row 1 and column 2 have values of 16" ## [1] "Row 2 and column 1 have values of 11" ## [1] "Row 2 and column 2 have values of 17" ## [1] "Row 3 and column 1 have values of 12" ## [1] "Row 3 and column 2 have values of 18" ## [1] "Row 4 and column 1 have values of 13" ## [1] "Row 4 and column 2 have values of 19" ## [1] "Row 5 and column 1 have values of 14" ## [1] "Row 5 and column 2 have values of 20" ## [1] "Row 6 and column 1 have values of 15" ## [1] "Row 6 and column 2 have values of 10"