0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Rで「あてはめ」ができるまでの道筋 制御構文

Last updated at Posted at 2023-10-25

制御構文

今回は制御構文を扱います。条件分岐と繰り返しです。繰り返しのfor やwhile は遅いので要注意です。(詳しくはこちらをご覧下さい)
これらはどのプログラミング言語にもあるものですが、言語によって書式が微妙に異なります。すなわち"else if"の代わりに"elif"を用いたり、{}が必要だったり必要でなかったり、...といった違いがあります。 本稿はR における制御構文の書式をまとめたものです。

条件分岐

if

言わずと知れた、もし◯◯◯ なら××× という構文です。
Rでは以下の書式で書きます。

if(a < 5) {
  print("yes")
} else {
  print("no")
}  

選択肢が複数ある場合はif ... else if ... else を使います。書式は以下の通りです。

if(a < 5) {
  print("low")
} else if(a < 8) {
  print("middle")
} else {
  print("high")	
}

switch

R にはswitch 構文はありますが、上記のif ... else if ... else の例を代替するようなものではないようです。詳細はこちらを参照してください。

ifelse

いわゆる3項演算子です。ifelse(A, B, C) の書式で、AがTRUE ならばB をFALSE ならばC を返す、というものです。

> h <- 10
> ampm <- ifelse(h<12, "AM", "PM")
> ampm
[1] "AM"

繰り返し

for

R にも他のプログラミング言語と同様にfor 文があります。R では以下のように書きます。

# example(A)
> for (i in 1:3) {
+ 	print(i)
+ }
[1] 1
[1] 2
[1] 3

蛇足の注意ですが、上記example(A)は

# example(B)
for (i in 1:3) {
	print(i)
}

を入力すると

[1] 1
[1] 2
[1] 3

という出力を得る、という意味です。行頭の">"や"+"を含めて入力してはいけません。ただ、エディタからexample(B)のように入力するとコンソールにはexample(A)のように表記されます。コンソールの表記をそのままコピペしたものがexample(A)です。

さて、注意すべきは、"1:3" という表現を用いると、3を「含む」ということです。Python やC など他のプログラミング言語に慣れた人にとってはとても違和感のあるところかもしれません。

while

while 文は以下の書式で書きます。

> i = 0
> while(i<3) {
+ 	print(i)
+ 	i <- i + 1
+ }
[1] 0
[1] 1
[1] 2

こちらはあまり違和感がないでしょう。

参考文献

biostatistics

トップページはこちら

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?