R 기초; 논리흐름 제어
x <- pi
y <- 3
if (x > y) x
[1] 3.141593
if (x < y) x
if (x < y) x else y
[1] 3
x <- pi
y < 1:5
if (x < y) x else y
[1] FALSE FALSE FALSE TRUE TRUE
test <- c(TRUE, FALSE, TRUE, TRUE, FALSE)
yes <- 1:5
no <- 0
ifelse(test, yes, no)
[1] 1 0 3 4 0
ifelse(x > y, x, y)
[1] 3.141593 3.141593 3.141593 4.000000 5.000000
center <- function(x, type) {
switch(type,
mean = mean(x),
median = median(x),
trimmed = mean(x, trim=0.1)
)
}
x <- c(2, 3, 5, 7, 11, 13, 17, 19, 23, 29)
center(x, "mean")
center(x, "median")
center(x, "trimmed")
center <- function(x, type) {
switch(type,
mean = mean(x),
median = median(x),
trimmed = mean(x, trim=0.1),
"Choose one of mean, median, and trimmed"
)
}
center(x, "other")
repeat print("hello")
i <- 5
repeat {if(i > 25) break
else {
print(i)
i <- 1+5
}
}
[1] 5
[1] 10
[1] 15
[1] 20
[1] 25
# while loop
i <- 5
while (i <= 25) {
print(i)
i <- i + 5
}
[1] 5
[1] 10
[1] 15
[1] 20
[1] 25
# for loop
x <- c(2, 5, 3, 9, 8, 11, 6)
count <- 0
for (val in x) {
if (val %% 2 == 0) count = count + 1
}
print(count)
[1] 3
# For Loop Statement Example # 01
fruit <- c('Apple', 'Orange', 'Passion fruit', 'Banana')
for (i in fruit) {
print(i)
}
[1] "Apple"
[1] "Orange"
[1] "Passion fruit"
[1] "Banana"
# For Loop Statement Example # 02
list <- c()
for (i in seq(1, 4, by=1)) {
list[[i]] <- i*i
}
print(list)
[1] 1 4 9 16
'공부 > R Programming' 카테고리의 다른 글
R 기초; 반복 적용 - Apply Family (0) | 2021.01.16 |
---|---|
R 기초; 서브셋 (0) | 2021.01.16 |
R 기초; 함수 Function (0) | 2021.01.16 |
R 기초; 출력 (0) | 2021.01.15 |
R 기초; 입력 (0) | 2021.01.15 |
댓글