R While Loop dengan Contoh Pemrograman
Sementara Loop dalam Pemrograman R
Perulangan While pada pemrograman R adalah pernyataan yang terus berjalan hingga suatu kondisi setelah blok while terpenuhi.
Sedangkan Sintaks Loop di R
Berikut ini adalah sintaks untuk While Loop dalam pemrograman R:
while (condition) { Exp }
Diagram Alir Perulangan Sementara R
Note: Ingatlah untuk menuliskan kondisi penutupan di beberapa titik, jika tidak, loop akan terus berlanjut tanpa batas.
Contoh Pemrograman While Loop pada R
Contoh 1
Mari kita bahas yang sangat sederhana Pemrograman R contoh untuk memahami konsep while loop. Anda akan membuat loop dan setelah setiap proses tambahkan 1 ke variabel yang disimpan. Anda perlu menutup perulangan, oleh karena itu kami secara eksplisit memberitahu R untuk menghentikan perulangan ketika variabel mencapai 10.
Note: Jika Anda ingin melihat nilai loop saat ini, Anda perlu memasukkan variabel ke dalam fungsi print().
#Create a variable with value 1 begin <- 1 #Create the loop while (begin <= 10){ #See which we are cat('This is loop number',begin) #add 1 to the variable begin after each loop begin <- begin+1 print(begin) }
Keluaran:
## This is loop number 1[1] 2 ## This is loop number 2[1] 3 ## This is loop number 3[1] 4 ## This is loop number 4[1] 5 ## This is loop number 5[1] 6 ## This is loop number 6[1] 7 ## This is loop number 7[1] 8 ## This is loop number 8[1] 9 ## This is loop number 9[1] 10 ## This is loop number 10[1] 11
Contoh 2
Anda membeli saham pada harga 50 dolar. Jika harganya turun di bawah 45, kami ingin menjualnya. Jika tidak, kami menyimpannya dalam portofolio kami. Harga dapat berfluktuasi antara -10 hingga +10 sekitar 50 setelah setiap putaran. Anda dapat menulis kode sebagai berikut:
set.seed(123) # Set variable stock and price stock <- 50 price <- 50 # Loop variable counts the number of loops loop <- 1 # Set the while statement while (price > 45){ # Create a random price between 40 and 60 price <- stock + sample(-10:10, 1) # Count the number of loop loop = loop +1 # Print the number of loop print(loop) }
Keluaran:
## [1] 2 ## [1] 3 ## [1] 4 ## [1] 5 ## [1] 6 ## [1] 7
cat('it took',loop,'loop before we short the price. The lowest price is',price)
Keluaran:
## it took 7 loop before we short the price. The lowest price is 40