[R] 조건문 (if)

2018. 6. 5. 14:18
R_if

조건문: if

R에서 조건문은 어떻게 쓸까? 다른 프로그래밍 언어들이 그러하듯 R도 if문을 쓴다.

  • if (expression_1) expression_2
    • 괄호 안의 조건문이 참이면 다음을 실행
  • if (expression_1) expression_2 else expression_3
    • 괄호 안의 조건문이 참이 아니면, expression_3을 실행
  • if else를 쓸 때에는 들여쓰기를 주의해야 함.
condition <- 1
x <- 100

if (condition == TRUE) 
{
  print("Hello, world!")
}
## [1] "Hello, world!"
if (x > 90) 
{
  print("more than 100")
} else # indent 주의 
{
  print("less than 100")
}
## [1] "more than 100"
  • if (expression_1) else if (expression_2) else expression_3도 가능.
check <- function(x)
{
  if(is.numeric(x) == TRUE | is.integer(x) == TRUE)
  {
    print("NUMBER")
  } 
  else if (is.character(x) == TRUE) 
  {
    print("CHARACTER")
  } 
  else
  {
    print("OTHERS")
  }
}
check(150); check("abc"); check(TRUE)
## [1] "NUMBER"
## [1] "CHARACTER"
## [1] "OTHERS"

Switch 함수

  • 조건문의 대상이 여러 개인 경우 사용할 수 있다.
  • else if를 반복해 사용하지 않아도 된다.
# 아래는 R help의 예제 
centre <- function(x, type) 
{
  switch(type,
         mean = mean(x),
         median = median(x))
}
x <- rcauchy(10) # 무작위로 수 10개 생성 
centre(x, "mean")
## [1] -0.6019167
centre(x, "median")
## [1] -0.4782902

ifelse

  • ifelse(test, yes, no)
    • test의 조건문이 참이면, yes 자리의 expression 실행.
    • test의 조건문이 거짓이면, no 자리의 expression 실행.
neg <- function(x)
{
  ifelse(x >= 0, "non-negative", "negative")
}

neg(3); neg(-10)
## [1] "non-negative"
## [1] "negative"