R 기초; 반복 적용 - Apply Family
apply()
lapply()
sapply()
mapply()
?apply
x <- matrix(1:20, 4, 5)
x
[,1] [,2] [,3] [,4] [,5]
[1,] 1 5 9 13 17
[2,] 2 6 10 14 18
[3,] 3 7 11 15 19
[4,] 4 8 12 16 20
apply(X=x, MARGIN=1, FUN=max)
[1] 17 18 19 20
apply(X=x, MARGIN=2, FUN=min)
[1] 1 5 9 13 17
y <- array(1:24, c(4, 3, 2))
, , 1
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
, , 2
[,1] [,2] [,3]
[1,] 13 17 21
[2,] 14 18 22
[3,] 15 19 23
[4,] 16 20 24
apply(y, 1, paste, collapse=",")
[1] "1,5,9,13,17,21" "2,6,10,14,18,22" "3,7,11,15,19,23" "4,8,12,16,20,24"
a <- c(1, 5, 9, 13, 17, 21)
a
[1] 1 5 9 13 17 21
paste(a)
[1] "1" "5" "9" "13" "17" "21"
paste(a, collapse=",")
[1] "1,5,9,13,17,21"
apply(y, 2, paste, collapse=",")
[1] "1,2,3,4,13,14,15,16" "5,6,7,8,17,18,19,20" "9,10,11,12,21,22,23,24"
apply(y, 3, paste, collapse=",")
[1] "1,2,3,4,5,6,7,8,9,10,11,12" "13,14,15,16,17,18,19,20,21,22,23,24"
apply(y, c(1, 2), paste, collapse=",")
[,1] [,2] [,3]
[1,] "1,13" "5,17" "9,21"
[2,] "2,14" "6,18" "10,22"
[3,] "3,15" "7,19" "11,23"
[4,] "4,16" "8,20" "12,24"
# 타이타닉 호 침몰 사건 데이터 불러오기
Titanic
# 데이터 구조 확인하기 str()
str(Titanic)
apply(Titanic, 1, sum)
1st 2nd 3rd Crew
325 285 706 885
apply(Titanic, 4, sum)
No Yes
1490 711
apply(Titanic, "Class", sum)
1st 2nd 3rd Crew
325 285 706 885
apply(Titanic, c(1, 4), sum)
Survived
Class No Yes
1st 122 203
2nd 167 118
3rd 528 178
Crew 673 212
lapply()
sapply()
# 연도별 시험점수 데이터 생성하기
exams <- list(s20=c(78,89,91,85,95,98), s21=c(85,86,97,99,90), s22=c(98,96,89,90,93,85,92), s23=c(98,96,91,88,93,99))
exams
$s20
[1] 78 89 91 85 95 98
$s21
[1] 85 86 97 99 90
$s22
[1] 98 96 89 90 93 85 92
$s23
[1] 98 96 91 88 93 99
# 연도별 학생수 알아보기
lapply(exams, length)
$s20
[1] 6
$s21
[1] 5
$s22
[1] 7
$s23
[1] 6
# 연도별 학생수
sapply(exams, length)
s20 s21 s22 s23
6 5 7 6
# 연도별 평균
sapply(exams, mean)
s20 s21 s22 s23
89.33333 91.40000 91.85714 94.16667
# 연도별 표준편차
sapply(exams, sd)
s20 s21 s22 s23
7.174027 6.348228 4.375255 4.262237
sapply(exams, range)
s20 s21 s22 s23
[1,] 78 85 85 88
[2,] 98 99 98 99
head(iris)
lapply(iris, class)
sapply(iris, class)
sapply(iris, mean)
sapply(iris, function(x), ifelse(is.numeric(x), mean(x), NA))
mapply(rep, 1:4, 4:1)
rep(1,4)
rep(2,3)
rep(3,2)
rep(4,1)
mapply(rep, 1:4, 4:1)
'공부 > R Programming' 카테고리의 다른 글
R기초; 분할-적용-결합 - dplyr (0) | 2021.01.17 |
---|---|
R 기초; 집단 요약 (0) | 2021.01.16 |
R 기초; 서브셋 (0) | 2021.01.16 |
R 기초; 논리흐름 제어 (0) | 2021.01.16 |
R 기초; 함수 Function (0) | 2021.01.16 |
댓글