R에서 여러 패키지를 로드하는 방법(예제 포함)


다음 기본 구문을 사용하여 여러 패키지를 R에 한 번에 로드할 수 있습니다.

 lapply(some_packages, library, character. only = TRUE )

이 예에서 some_packages는 로드하려는 패키지 이름의 벡터를 나타냅니다.

다음 예에서는 실제로 이 구문을 사용하는 방법을 보여줍니다.

예: R에서 여러 패키지 로드

다음 코드는 R에서 데이터 세트를 요약하고 세 가지 다른 패키지를 사용하여 플롯을 생성하는 방법을 보여줍니다.

  • dplyr
  • ggplot2
  • gg테마

이 예에서는 세 가지 다른 library() 함수를 사용하여 각 패키지를 개별적으로 로드합니다.

 library (dplyr)
library (ggplot2)
library (ggthemes)

#make this example reproducible
set. seeds (0)

#create data frame
df <- data. frame (category=rep(c('A', 'B', 'C', 'D', 'E'), each= 10 ),
                 value=runif(50, 10, 20))

#create summary data frame
df_summary <- df %>%
  group_by(category) %>%
  summarize(mean=mean(value),
            sd=sd(value))

#plot mean value of each category with error bars
ggplot(df_summary) +
    geom_bar(aes(x=category, y=mean), stat=' identity ') +
    geom_errorbar(aes(x=category, ymin=mean-sd, ymax=mean+sd), width= 0.3 ) +
    theme_tufte()

이 코드를 사용하면 세 가지 패키지를 모두 로드하고 데이터 세트의 값을 요약하는 차트를 생성할 수 있습니다.

그러나 lapply() 함수를 사용하여 한 줄의 코드로 세 패키지를 모두 로드하면 동일한 결과를 얻을 수 있습니다.

 #define vector of packages to load
some_packages <- c(' ggplot2 ', ' dplyr ', ' ggthemes ')

#load all packages at once
lapply(some_packages, library, character. only = TRUE )

#make this example reproducible
set. seeds (0)

#create data frame
df <- data. frame (category=rep(c('A', 'B', 'C', 'D', 'E'), each= 10 ),
                 value=runif(50, 10, 20))

#create summary data frame
df_summary <- df %>%
  group_by(category) %>%
  summarize(mean=mean(value),
            sd=sd(value))

#plot mean value of each category with error bars
ggplot(df_summary) +
    geom_bar(aes(x=category, y=mean), stat=' identity ') +
    geom_errorbar(aes(x=category, ymin=mean-sd, ymax=mean+sd), width= 0.3 ) +
    theme_tufte() 

다시 한 번 세 가지 패키지를 모두 로드하고 이전과 동일한 플롯을 생성할 수 있습니다.

차이점은 이번에는 한 줄의 코드를 사용하여 세 가지 패키지를 모두 로드할 수 있다는 것입니다.

lapply() 함수는 매번 library() 함수를 입력하지 않고 긴 패키지 목록을 로드하려는 경우 특히 유용합니다.

추가 리소스

다음 튜토리얼에서는 R에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.

R에서 환경을 지우는 방법
RStudio에서 모든 플롯을 지우는 방법
R에서 해석하는 방법: 다음 개체가 숨겨져 있습니다.

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다