기본 콘텐츠로 건너뛰기

pandas_ta를 적용한 통계적 인덱스 지표

R apply, lapply, sapply 그리고 tapply함수

Applying functions

자료에서 원자별, 그룹별로 함수등을 적용할 경우 apply 계열의 함수를 사용합니다. 예를 들어 행렬, 배열, 데이터 프레임의 지정된 차원에 함수를 적용하거나 리스트의 각 인덱스별로 함수등을 적용할 경우 control 문을 대신하여 사용합니다. 이 계열의 함수들의 기본 목적은 같지만 입력과 출력의 데이터 형태에서 차이를 보입니다.
apply(x, margin, Fun, ...)
margin: 차원인덱스, Fun: 적용할 함수
입력: array, dataframe, 출력: vector, list, array
lapply(x, Fun, ...)
입력: list, vector, dataframe, 출력: list
sapply(x, Fun, ...)
입력: list, vector, dataframe, 출력: vector, array
lapply()와 동일하지만 벡터나 배열을 출력
tapply(x, index, Fun, ...)
index: factor를 포함한 list
입력: list, vector, factor, dataframe, 출력: vector, array
set.seed(10)
da<-round(matrix(runif(24), 6, 4), 3)
colnames(da)<-c('one', 'two', 'three', 'four')
rownames(da)<-paste('case', 1:6, sep=' ')
head(da, 2)
         one   two three  four
case 1 0.507 0.275 0.114 0.399
case 2 0.307 0.272 0.596 0.836
행기준의 평균
apply(da, 1, mean)
 case 1  case 2  case 3  case 4  case 5  case 6
0.32375 0.50275 0.56650 0.54175 0.39100 0.35325
열기준의 평균
apply(da, 2, mean)
      one       two     three      four
0.3740000 0.4688333 0.3021667 0.6410000
열기준으로 최대와 최소 20%를 절삭하는 trim mean을 계산합니다.
apply(da, 2, mean, trim=0.2)
    one     two   three    four
0.36650 0.47225 0.29125 0.65625
다음 객체는 학생들의 이름으로 구성된 벡터로 각 학생의 fistname만으로 구성된 객체를 생성합니다.
Student <- c("John Davis", "Angela Williams", "Bullwinkle Moose",
 "David Jones", "Janice Markhammer", "Cheryl Cushing",
 "Reuven Ytzrhak", "Greg Knox", "Joel England",
 "Mary Rayburn")
 name<-strsplit(Student, ' ')
[[1]]
[1] "John"  "Davis"

[[2]]
[1] "Angela"   "Williams"
⋮
[[10]]
[1] "Mary"    "Rayburn"
fNameL<-lapply(name, '[', 1); fNameL
[[1]]
[1] "John"
⋮
[[10]]
[1] "Mary"
위 함수에 적용된 '['는 객체의 부분을 분취하기 위한 함수입니다. 위 객체는 list이므로 unlist() 함수를 사용하여 vector로 전환할 수 있습니다.
fNameV<-unlist(fNameL); fNameV
[1] "John"       "Angela"     "Bullwinkle" "David"      "Janice"    
 [6] "Cheryl"     "Reuven"     "Greg"       "Joel"       "Mary"
위의 lapply() 적용 결과를 벡터로 전환하는 과정은 sapply()함수를 사용하는 것으로 생략할 수 있습니다.
sapply(name, '[', 1)
[1] "John"       "Angela"     "Bullwinkle" "David"      "Janice"
 [6] "Cheryl"     "Reuven"     "Greg"       "Joel"       "Mary" 
lapply(), sapply()함수를 dataframe에 적용할 경우 열기준으로 작동됩니다. 위의 데이터 da를 dataframe 형식으로 전환하여 두 함수를 적용한 결과는 다음과 같습니다.
daf<-as.data.frame(da); daf
         one   two three  four
case 1 0.507 0.275 0.114 0.399
…
lapply(daf, mean)
$one
[1] 0.374

$two
[1] 0.4688333
⋮
sapply(daf, sd)
      one       two     three      four 
0.2156247 0.1690354 0.2024791 0.2220910
tapply()는 벡터의 각 요인 변수에 대한 측정값(평균, 중앙값, 최소값, 최대값 등) 또는 함수를 계산합니다. 벡터의 하위 집합을 만든 다음 각 하위 집합에 일부 기능을 적용할 수 있는 매우 유용한 기능입니다.
data(iris)
head(iris)
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa
이 자료의 구조는 dataframe이지만 각 열 자료는 다음의 형태를 가집니다.
sapply(iris, class)
 Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
   "numeric"    "numeric"    "numeric"    "numeric"     "factor" 
위 결과와 같이 Species 열은 factor이므로 levels() 함수를 사용하여 고유값을 확인할 수 있습니다.
levels(iris$Species)
 [1] "setosa"     "versicolor" "virginica"
위 결과는 중복값을 제거하고 고유값만을 반환하는 unique()함수를 사용할 수 있습니다. 이 함수의 결과는 factor 형입니다.
unique(iris$Species)
 [1] setosa     versicolor virginica 
Levels: setosa versicolor virginica
자료 iris에서 Sepal.Length를 Species의 각 수준(level)로 그룹화하여 각 그룹의 평균들 계산합니다. 이 계산은 tapply()함수를 적용합니다.
with(iris, {
+     meanLen<<-tapply(Sepal.Length, Species, mean)
+ })
meanLen
 setosa versicolor  virginica
    5.006      5.936      6.588

댓글