[Fast campus] Data Science with R 1기 - 이부일 강사님

공부하면서 배운 내용 복습 겸 정리하는 곳입니다.


# R.utils 패키지를 통해 printf() 사용 가능

install.packages("R.utils")

library(R.utils)


1. 반복문 : for

  # 동일한 일을 여러 번 하거나

  # 비슷한 일을 여러 번 할 때

1
2
3
4
5
6
7
8
9
10
11
12
13
> for(i in 1:10){
+   cat("hello,", i, "\n")
+ }
hello, 1 
hello, 2 
hello, 3 
hello, 4 
hello, 5 
hello, 6 
hello, 7 
hello, 8 
hello, 9 
hello, 10
cs

  # in은 대입, 할당하는 역할

  # 1:10 => 데이터의 개수(10개) 만큼 for문이 시행된다.

  # cat 대신 printf("hello, %d \n", i) 를 사용해도 동일한 결과 출력


  # 구구단

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
> for(i in 1:9){
+   cat(i, "단 이에요!""\n")
+   for(j in 1:9){
+     cat(i, "x", j, "=", i*j, "\n")
+   }
+   cat("\n")
+ }
 
1 단 이에요! 
1 x 1 = 1 
1 x 2 = 2 
1 x 3 = 3 
1 x 4 = 4 
1 x 5 = 5 
1 x 6 = 6 
1 x 7 = 7 
1 x 8 = 8 
1 x 9 = 9 
...
cs

  # 2~9단도 동일한 결과로 출력됨



2. 조건문

  (1) if( 조건 ){ 실행문 } - 조건이 TRUE면 실행문을 실행

1
2
3
4
5
6
7
8
9
> x = c(1003060)
> for(i in 1:3){
+   if(x[i] > 50){
+     printf("%d Very large number!!! \n", x[i])
+   } 
+ }
 
100 Very large number!!! 
60 Very large number!!!
cs


  (2) if (조건문) { 조건이 참일 때 실행문 1} 
       else{ 조건이 거짓일 때 실행문 2}

1
2
3
4
5
6
7
8
> y  = 10
> if(y > 5){
+   print("Large!!")
+ } else{
+   print("Small!!")
+ }
 
[1"Large!!"
cs


  (3) if( 조건문1) { 실행문 1 }

      else if( 조건문 2) { 실행문 2}

      else{ 실행문 3 }

# else if 조건 추가 가능

1
2
3
4
5
6
7
8
9
10
> z = 7
> if(z>10){
+   print("Large")
+ } else if(z>5){
+   print("medium")
+ } else{
+   print("small")
+ }
 
[1"medium"
cs



3. 사용자 함수

  # 함수명 = function( ) { 실행문 }

1
2
3
4
5
6
7
8
9
10
11
12
> hello = function(){
+   print("hello, world")
+   return("hello, fastcampus")
+ }
 
> hello()
[1"hello, world"
[1"hello, fastcampus"
 
> x = hello()
> x
[1"hello, world"
cs

  # return 의 의미를 생각


  # 숫자 x를 입력받으면 x*3 을 해주는 함수 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
> triple = function(x){
+   if(mode(x) == "numeric"){
+  #if(is.numeric(x)) 을 사용해도 된다
+     tmp = 3*x
+     return (tmp)
+   } else{
+     print("숫자를 넣어주세요")
+   }
+ }
 
> triple(10)
[130
 
> triple("10")
[1"숫자를 넣어주세요"
cs


  # 구구단 : 해당 숫자의 구구단을 출력

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
> gugudan = function(x){
+   if(is.numeric(x)){
+     printf("%d단 \n", x)
+     for(i in 1:9){
+       printf("%d x %d = %d \n", x,i,x*i)
+     }
+   } else{
+     print("숫자를 넣어주세요")
+   }
+ }
 
> gugudan(3)
3단 
3 x 1 = 3 
3 x 2 = 6 
3 x 3 = 9 
3 x 4 = 12 
3 x 5 = 15 
3 x 6 = 18 
3 x 7 = 21 
3 x 8 = 24 
3 x 9 = 27
cs


+ Recent posts