R 中的 For 循环以及列表和矩阵的示例

当我们需要迭代元素列表或数字范围时,for 循环非常有用。循环可用于迭代列表、数据框、向量、矩阵或任何其他对象。括号和方括号是必需的。

在本教程中,我们将学习,

For 循环语法和示例

For (i in vector) {
    Exp	
}

在这里,

R 将循环遍历向量中的所有变量并执行 exp 中写的计算。

R 中的 For 循环
R 中的 For 循环

我们来看几个例子。

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:使用 1 到 4 之间的 x 多项式创建一个非线性函数,并将其存储在列表中

# 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 循环迭代一系列值并定义最佳候选值。

循环遍历列表

循环遍历列表与循环遍历向量一样简单方便。让我们看一个例子

# 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 循环

矩阵有二维,即行和列。要迭代矩阵,我们必须定义两个 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"