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 ループを使用して値の範囲を反復し、最適な候補を定義できます。

リストに対する 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 次元の行と列を持ちます。 行列を反復するには、XNUMX つの for ループ、つまり行用と列用に XNUMX つを定義する必要があります。

# 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"