R တွင် အပိုင်းအခြားပါသော ကွင်းဆက်အတွက် (ဥပမာများအပါအဝင်)
R တွင် အကွာအဝေးတစ်ခုပါရှိသော for loop တစ်ခုကို ရေးသားရန် အောက်ပါအခြေခံ syntax ကို သင်အသုံးပြုနိုင်သည်-
for (i in 1:10) { do something }
အောက်ဖော်ပြပါ ဥပမာများသည် ဤ syntax ကို လက်တွေ့တွင် မည်သို့အသုံးပြုရမည်ကို ပြသထားသည်။
ဥပမာ 1: အပိုင်းအခြားရှိ တန်ဖိုးများကို ပုံနှိပ်ပါ။
အောက်ပါကုဒ်သည် သတ်မှတ်ထားသော အတိုင်းအတာတစ်ခုအတွင်း တန်ဖိုးတစ်ခုစီကို ပရင့်ထုတ်ရန်အတွက် for loop ကို အသုံးပြုပုံကို ပြသသည်-
#print every value in range of 1 to 10 for (i in 1:10) { print(i) } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 [1] 6 [1] 7 [1] 8 [1] 9 [1] 10
ဥပမာ 2: အပိုင်းအခြားရှိ တန်ဖိုးများအပေါ် လုပ်ဆောင်ချက်တစ်ခု လုပ်ဆောင်ပါ။
အောက်ဖော်ပြပါ ကုဒ်သည် သတ်မှတ်ထားသော အတိုင်းအတာတစ်ခုအတွင်း တန်ဖိုးတစ်ခုစီအတွက် သီးခြားလုပ်ဆောင်မှုတစ်ခုကို လုပ်ဆောင်ရန် for loop ကို အသုံးပြုပုံကို ပြသသည်-
#definevector x <- c(4, 7, 9, 12, 14, 16, 19) #print square root of every value in vector for (i in 1: length (x)) { print(paste(' The square root of the value in position ', i, ' is ', sqrt(x[i]))) } [1] "The square root of the value in position 1 is 2" [1] "The square root of the value in position 2 is 2.64575131106459" [1] "The square root of the value in position 3 is 3" [1] "The square root of the value in position 4 is 3.46410161513775" [1] "The square root of the value in position 5 is 3.74165738677394" [1] "The square root of the value in position 6 is 4" [1] "The square root of the value in position 7 is 4.35889894354067"
ဥပမာ 3: ဒေတာဘောင်ရှိ တန်ဖိုးများအပေါ် လုပ်ဆောင်ချက်တစ်ခု လုပ်ဆောင်ပါ။
အောက်ပါကုဒ်သည် r ရှိ ဒေတာဘောင်တစ်ခု၏ သီးခြားကော်လံတစ်ခုစီ၏ တန်ဖိုးတစ်ခုစီအတွက် တိကျသောလုပ်ဆောင်ချက်တစ်ခုလုပ်ဆောင်ရန် for loop ကိုအသုံးပြုပုံကို ပြသသည်-
#define data frame
df <- data. frame (a=c(3, 4, 4, 5, 8),
b=c(8, 8, 7, 8, 12),
c=c(11, 15, 19, 15, 11))
#view data frame
df
ABC
1 3 8 11
2 4 8 15
3 4 7 19
4 5 8 15
5 8 12 11
#multiply every value in column 'a' by 2
for (i in 1: length (df$a)) {
df$a[i] = df$a[i]*2
}
#view updated data frame
df
ABC
1 6 8 11
2 8 8 15
3 8 7 19
4 10 8 15
5 16 12 11
ထပ်လောင်းအရင်းအမြစ်များ
R တွင် nested For loop ဖန်တီးနည်း
R တွင် If Else ကြေငြာချက် nested ကိုဘယ်လိုရေးရမလဲ
R တွင် ကော်လံအမည်များကို မည်သို့ပြန်ဆိုရမည်နည်း။