오늘 할 일: 갈고 닦기
article thumbnail

R에서 원소에 동일한 연산을 반복적으로 수행하고 싶을 때 apply 계열의 함수를 사용합니다. 일반적으로 반복 계산을 할 때 사용하는 for, while보다 시간이 적게 듭니다.

 

1. apply()

  • 행렬이나 데이터 프레임의 행, 열에 대해 함수를 적용할 때 사용합니다.
  • apply(x, margin, function)
    • margin = 1 : 행에 대한 연산
    • margin = 2 : 열에 대한 연산
    • margin = c(1,2) : 원소에 대한 연산

 

2. lapply()

  • 리스트에 적용하며 결과 역시 리스트로 반환합니다.
  • lapply(x, function)

 

3. sapply()

  • lapply()와 유사한데요, lapply()는 결과를 리스트로 반환하는 반면 sapply()는 결과를 벡터나 행렬로 반환합니다.

위 예제와 결과 값은 동일하지만 자료형이 다릅니다.

 

4. tapply()

  • 첫번째 인자에 대해 두번째 인자의 수준별로 함수를 적용합니다
  • tapply(x, factor, function)

the result of `boxplot(x ~ fac)`

iris 데이터를 사용하여 꽃의 종류별(Species)로 꽃받침의 너비(Sepal.Width) 평균을 계산하면 다음과 같습니다. 

 

참고자료

https://www.guru99.com/r-apply-sapply-tapply.html

 

apply(), lapply(), sapply(), tapply() Function in R with Examples

With many Database Warehousing tools available in the market, it becomes difficult to select the...

www.guru99.com

https://www.learnbyexample.org/r-apply-functions/

 

apply(), lapply(), sapply() and tapply() Functions in R - Learn By Example

R has a more efficient and quick approach to perform iterations with the apply family. Learn more about apply(), lapply(), sapply() and tapply() functions.

www.learnbyexample.org