สำหรับ Loop ใน R พร้อมตัวอย่างสำหรับรายการและเมทริกซ์
ลูป for มีประโยชน์มากเมื่อเราต้องทำซ้ำรายการขององค์ประกอบหรือช่วงของตัวเลข ลูปสามารถใช้เพื่อทำซ้ำรายการ เฟรมข้อมูล เวกเตอร์ เมทริกซ์ หรืออ็อบเจ็กต์อื่น ๆ วงเล็บปีกกาและวงเล็บเหลี่ยมเป็นข้อบังคับ
ในบทช่วยสอนนี้ เราจะเรียนรู้
สำหรับไวยากรณ์และตัวอย่างลูป
For (i in vector) { Exp }
ที่นี่
R จะวนซ้ำตัวแปรทั้งหมดในเวกเตอร์และทำการคำนวณที่เขียนภายใน exp

เรามาดูตัวอย่างกัน
สำหรับการวนซ้ำใน R ตัวอย่างที่ 1: เราวนซ้ำองค์ประกอบทั้งหมดของเวกเตอร์และพิมพ์ค่าปัจจุบัน
# Create fruit vector fruit <- c('Apple', 'Orange', 'Passion fruit', 'Banana') # Create the for statement for ( i in fruit){ print(i) }
Output:
## [1] "Apple" ## [1] "Orange" ## [1] "Passion fruit" ## [1] "Banana"
สำหรับการวนซ้ำใน R ตัวอย่างที่ 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)
Output:
## [1] 1 4 9 16
for loop มีค่ามากสำหรับงานแมชชีนเลิร์นนิง หลังจากที่เราฝึกโมเดลแล้ว เราจำเป็นต้องปรับโมเดลให้เป็นปกติเพื่อหลีกเลี่ยงไม่ให้มีการติดตั้งมากเกินไป การทำให้เป็นมาตรฐานเป็นงานที่น่าเบื่อมากเพราะเราจำเป็นต้องค้นหาค่าที่ลดฟังก์ชันการสูญเสียให้เหลือน้อยที่สุด เพื่อช่วยให้เราตรวจจับค่าเหล่านั้น เราสามารถใช้ for loop เพื่อวนซ้ำช่วงของค่าและกำหนดตัวเลือกที่ดีที่สุด
สำหรับวนรอบรายการ
การวนซ้ำรายการนั้นง่ายและสะดวกพอๆ กับการวนซ้ำบนเวกเตอร์ มาดูตัวอย่างกัน
# 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) }
Output:
## [1] "Apple" "Orange" "Passion fruit" "Banana" ## [1] 10 12 15 ## [1] FALSE
สำหรับลูปบนเมทริกซ์
เมทริกซ์มี 2 มิติ แถวและคอลัมน์ ในการวนซ้ำเมทริกซ์ เราต้องกำหนด for loop สองรายการ กล่าวคือหนึ่งรายการสำหรับแถวและอีกรายการหนึ่งสำหรับคอลัมน์
# 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]))
Output:
## [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"