## [1] 2
## [1] 4
## [1] 6
## [1] 8
## [1] 10
# for 반복문 후 벡터만들기
result <- c()
for (i in 1:length(x)){
if(x[i] %% 2 == 0) # 2로 나누어 나머지가 0인 입력값만 프린트
result <- c(result, x[i])
}
result
## [1] 2 4 6 8 10
## 'data.frame': 15 obs. of 3 variables:
## $ height: num 58 59 60 61 62 63 64 65 66 67 ...
## $ weight: num 115 117 120 123 126 129 132 135 139 142 ...
## $ AB : chr "" "" "" "" ...
for (i in 1:length(women)){
if(women[i,1] > mean(women$height)){
women[i,3] <- "A"
} else {women[i,3] <- "B"}
}
women
## height weight AB
## 1 58 115 B
## 2 59 117 B
## 3 60 120 B
## 4 61 123
## 5 62 126
## 6 63 129
## 7 64 132
## 8 65 135
## 9 66 139
## 10 67 142
## 11 68 146
## 12 69 150
## 13 70 154
## 14 71 159
## 15 72 164
## [1] "짝수"
## [1] "홀수"
# 조건 3개 일때
x <- 102
if (x %% 3 == 0) {
y <- "3의 배수"
print(y)
} else if (x %% 3 == 1) {
y <- "나머지 1"
print(y)
} else {
y <- "나머지 2"
print(y)
}
## [1] "3의 배수"
## [1] "A" "B" "B"
## [1] "C" "C" "B"
odd.even <- function(x){
if(x%%2==1) result <- "홀수" else result <- "짝수"
print(result)
}
odd.even(1999)
## [1] "홀수"
## [1] "짝수"
# 2개의 제곱합 구하기
sum_func_return <- function(x, y) { # default값을 지정하지 않아도 된다.
res <- x^2 + y^2
return(res) # cat(res)과 차이
}
sum_func_return(2,3)
## [1] 13
# numeric column 평균 구하기
res <- c()
numeric_col_means <- function(data){
cols <- colnames(data)
for(i in cols){
tmp_col <- data[[i]]
if(class(tmp_col) == "numeric"){
col_avg <- mean(tmp_col)
res <- c(res, col_avg)
}
}
return(res)
}
str(iris)
## 'data.frame': 150 obs. of 5 variables:
## $ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
## $ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
## $ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
## $ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
## $ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
## [1] 5.843333 3.057333 3.758000 1.199333