[R] 조건문
Y
Yerim
- R
if (비교 조건){
조건이 참일 떄 실행할 명령문(들)
} else {
조건이 거짓일 때 실행할 명령문(들)
}ifelse(비교 조건, 조건이 참일 때 선택할 값, 조건이 거짓일 때 선택할 값# LAB.
library(svDialogs)
# 구매액 입력 받기
purchase <- dlgInput('Enter the purchase amount')$res
purchase <- as.numeric(purchase)
type <- NULL
ratio <- NULL
# 조건문 수정
if (purchase >= 300000) {
type <- '플래티넘'
ratio <- 0.07
} else if (purchase >= 200000) {
type <- '골드'
ratio <- 0.05
} else if (purchase >= 100000) {
type <- '실버'
ratio <- 0.03
} else {
type <- '프렌즈'
ratio <- 0.01
}
# 결과 출력
cat('고객님은', type, '회원으로 구매액의', ratio * 100, '%가 적립됩니다.\n')# 코드 7-18
score <- c(76, 84, 59, 50, 95, 60, 82, 71, 88, 84)
which(score == 69)
which(score >= 85)
max(score)
which.max(score)
min(score)
which.min(score)# 코드 7-19
score <- c(76, 84, 69, 50, 95, 60, 82, 71, 88, 84)
idx <- which(score <= 60)
score[idx] <- 61
score
idx <- which(score >= 80)
score.high <- score[idx]
score.high# LAB.
install.packages('Stat2Data')
library(Stat2Data)
data(ChildSpeaks)
str(ChildSpeaks)
# 말문이 트인 시기는 age에 저장
idx <- which(ChildSpeaks$Age < 9)
ChildSpeaks[idx, 'm1'] <- 5
idx <- which(ChildSpeaks$Age >= 9 & ChildSpeaks$Age < 15)
ChildSpeaks[idx, 'm1'] <- 4
idx <- which(ChildSpeaks$Age >= 15 & ChildSpeaks$Age < 21)
ChildSpeaks[idx, 'm1'] <- 3
idx <- which(ChildSpeaks$Age >= 21 & ChildSpeaks$Age < 27)
ChildSpeaks[idx, 'm1'] <- 2
idx <- which(ChildSpeaks$Age >= 27)
ChildSpeaks[idx, 'm1'] <- 1
ChildSpeaks$m1
# 언어 이해력은 Gesell에 저장
idx <- which(ChildSpeaks$Gesell < 70)
ChildSpeaks[idx, 'm2'] <- 1
idx <- which(ChildSpeaks$Gesell >= 70 & ChildSpeaks$Gesell < 90)
ChildSpeaks[idx, 'm2'] <- 2
idx <- which(ChildSpeaks$Gesell >= 90 & ChildSpeaks$Gesell < 110)
ChildSpeaks[idx, 'm2'] <- 3
idx <- which(ChildSpeaks$Gesell >= 110 & ChildSpeaks$Gesell < 130)
ChildSpeaks[idx, 'm2'] <- 4
idx <- which(ChildSpeaks$Gesell >= 130)
ChildSpeaks[idx, 'm2'] <- 5
ChildSpeaks$total <- ChildSpeaks$m1 + ChildSpeaks$m2
idx <- which(ChildSpeaks$total < 3)
ChildSpeaks[idx, 'result'] <- '매우 느림'
idx <- which(ChildSpeaks$total >= 3 & ChildSpeaks$total < 5)
ChildSpeaks[idx, 'result'] <- '늦음'
idx <- which(ChildSpeaks$total >= 5 & ChildSpeaks$total < 7)
ChildSpeaks[idx, 'result'] <- '보통'
idx <- which(ChildSpeaks$total >= 7 & ChildSpeaks$total < 9)
ChildSpeaks[idx, 'result'] <- '빠름'
idx <- which(ChildSpeaks$total >= 9)
ChildSpeaks[idx, 'result'] <- '매우 빠름'
ChildSpeaks
ChildSpeaks[which.min(ChildSpeaks$total), ]