[R] - focats/facor , 레벨(level) 순서 조정 - tidyverse 생태계에 적응해보자

반응형

이번에는 팩터(Factor)를 효과적으로 처리할 수 있는 함수를 제공하는 라이브러리 forcats의 사용에 대한 내용입니다. 

 

기본적으로 다루게 되는 base 패키지로도 factor를 충분히 다룰 수 있지만 forcats 패키지를 활용하면 factor를 보다 효율적이고 일관된 방식으로 처리할 수 있습니다. 특히 forcats 패키지는 Tidyverse 생태계의 일부이기 때문에 그 생태계에 속한 패키지 및 함수와 함께 사용하면 더욱 효과적입니다. 

 

# 팩터 - factors 

c("Vegetables", "Fruits", "Vegetables", "Grains","Fruits",
  "Vegetables", "Dairy", "Fruits", "Proteins", "Fruits")

food <- factor(c("Vegetables", "Fruits", "Vegetables", "Grains","Fruits",
                 "Vegetables", "Dairy", "Fruits", "Proteins", "Fruits"))
food

install.packages('forcats')
library(forcats)
fct_inorder(food)

fct_infreq(food) # 출연빈도가 많은 순서

fct_relevel(food, "Fruits", "Vegetables", "Grains", "Proteins", 
            "Dairy") # level 순서를 사용자가 지정

fct_relevel(food, "Proteins")
fct_relevel(food, "Dairy")

fct_relevel(food, "Proteins", after=2) # after=2는 2번째 위치 뒤 
fct_relevel(food, "Proteins", after=Inf)

value <- c(1000, 1500, 1200, 700, 2000,
           2000, 1350, 2500, 15000, 3000)

food

fct_reorder(food, .x=value) # .x에는 level의 순서를 정할 기준
fct_reorder(food, .x=value, .fun=mean) # .fun에 mean 적용 

fct_reorder(food, .x=value, .desc = TRUE)

fct_recode(food, Fats="Proteins", Fats="Dairy") # 기존이름 변경 가능.
반응형