< 4 > 제어문과 함수
4-1) 반복문
for()
for (variable in vector){
# 반복할 식
}
4-2) 조건문
if(조건식){참인 경우 처리문} else {거짓말 경우 처리문}
if(100 %% 2 == 0){
print(100 %% 2)
}else{
print(100)
}
if(조건식){참인 경우 처리문} else if(조건식){참인경우 처리문} else {거짓일 경우 처리문}
score <- sample(50:100,1)
if(score>=60){result = "A학점"
} else if(score >= 30){result = "B학점"
} else if(score >= 10){result = "C학점"
} else {result = "F학점"}
print(result)
ifelse(조건식, 참인경우 처리문, 거짓인 경우 처리문)
ifelse(score>=80, "수석", "보통")
iris$con <- ifelse(iris$Sepal.Length > 5.0, "넓다", "좁다")
iris$con <- ifelse(iris$Sepal.Length > 5.0, "넓다",
ifelse(iris$Sepal.Length>3, "보통", "좁다")) # 중첩 조건문도 가능
4-3) for문 안에 if문
for(n in 1:10){
if(n%%2==0){
next # 다음 문장으로 skip
} else {
print(n)
}
}
for(n in 1:10){
if(n%%2==0){
print("짝수")
} else
if(n%%2==1){
print("홀수")
}
}
4-4) switch()
#기준에 맞으면 실행
xxx <- c(2,3,4,2)
switch(xxx[2],
"1"=print("one"),
"2"=print("two"),
"3"=print("three"),
print("not")
)
4-5) 사용자 정의 함수
함수 : 입력된 값을 받아 정해진 방식으로 출력
사용자 정의 함수 : 원하는 기능을 사용자가 직접 만듦
구조 : 함수명 <- function(입력되는 값 저장 변수){실행 1, 실행 2 ... return(결과 값)}
ex1 <- function(x){
if(x %% 2==0) # 2로 나누었을때 나머지가 0
{x^2}
else { return(0)}
}
ex1(14)
ex2 <- function(x){
ifelse(x > 5, "5보다 큰수", 0)
}
ex2(7.5)
ex3 <- function(x){
ifelse(x == '라떼', 'Very Good',
ifelse(x == '아메리카노', 'Good',
ifelse(x == '모카', "So So", "메뉴에 없어요")))
}
ex3("아메리카노")
Q. 외부 데이터 (TXT 파일) 가공 연습
#ex) power reactor staus reports (미국 원자력 발전소)
# 방법 1. url에서 읽기
web_url <- "https://www.nrc.gov/reading-rm/doc-collections/event-status/reactor-status/PowerReactorStatusForLast365Days.txt"
web_url
library(dplyr)
library(ggplot2)
power1 <- read.table(web_url, header = T, sep = "|", stringsAsFactors = T)
#stringsAsFactors : 외부에서 데이터 가져올 때 숫자말고 문자들이 factor가되는 현상이 발생 방지
str(power1)
qplot(power1$Power)
power1$con <- ifelse(power1$Power < 100, "낮음", "높음")
qplot(power1$con)
str(power1$con)
power1$con <- factor(power1$con, levels= c("높음","낮음")) # 레벨 순서 지정
qplot(power1$con)
power1$ReportDt <- as.Date(power1$ReportDt, "%m/%d/%Y") # Factor -> Date
str(power1$ReportDt)
#방법 2. 다른이름으로 링크 저장 -> txt 파일로 저장 ->
Rstudio 에서 <file-Import Dataset - From Text(readr)>