R에서 attachment()를 사용하는 방법(예제 포함)


R의 attachment() 함수를 사용하면 데이터 프레임 이름을 입력하지 않고도 데이터 프레임 객체에 액세스할 수 있습니다.

이 함수는 다음 기본 구문을 사용합니다.

 attach(data)

다음 예에서는 다음 데이터 프레임을 사용하여 다양한 시나리오에서 이 함수를 사용하는 방법을 보여줍니다.

 #create data frame
df <- data. frame (team=c('A', 'B', 'C', 'D', 'E'),
                 points=c(99, 90, 86, 88, 95),
                 assists=c(33, 28, 31, 39, 34),
                 rebounds=c(30, 28, 24, 24, 28))

#view data frame
df

  team points assists rebounds
1 A 99 33 30
2 B 90 28 28
3 C 86 31 24
4 D 88 39 24
5 E 95 34 28

예 1: 계산 수행을 위해 attachment() 사용

일반적으로 평균, 중앙값, 범위 등을 계산하려는 경우 데이터 프레임의 열에 대해 다음 구문을 사용합니다.

 #calculate mean of rebounds column
mean(df$rebounds)

[1] 26.8

#calculate median of rebounds column
median(df$rebounds)

[1] 28

#calculate range of rebounds column
range(df$rebounds)

[1] 24 30

그러나 attachment() 를 사용하면 이러한 계산을 수행하기 위해 데이터 프레임 이름을 입력할 필요조차 없습니다.

 attach(df)

#calculate mean of rebounds column
mean(rebounds)

[1] 26.8
#calculate median of rebounds column
median(rebounds)

[1] 28
#calculate range of rebounds column
range(rebounds)

[1] 24 30

Attach()를 사용하면 열 이름을 직접 참조할 수 있으며 R은 우리가 사용하려는 데이터 프레임을 알 수 있습니다.

예 2: 회귀 모델에 적합하도록 attachment() 사용

일반적으로 R에 선형 회귀 모델을 적용하려면 다음 구문을 사용합니다.

 #fit regression model
fit <- lm(points ~ assists + rebounds, data=df)

#view coefficients of regression model
summary(fit)$coef

              Estimate Std. Error t value Pr(>|t|)
(Intercept) 18.7071984 13.2030474 1.416885 0.29222633
assists 0.5194553 0.2162095 2.402555 0.13821408
rebounds 2.0802529 0.3273034 6.355733 0.02387244

그러나 attachment() 를 사용하면 회귀 모델에 맞추기 위해 lm() 함수의 data 인수를 사용할 필요조차 없습니다.

 #fit regression model
fit <- lm(points ~ assists + rebounds)

#view coefficients of regression model
summary(fit)$coef

              Estimate Std. Error t value Pr(>|t|)
(Intercept) 18.7071984 13.2030474 1.416885 0.29222633
assists 0.5194553 0.2162095 2.402555 0.13821408
rebounds 2.0802529 0.3273034 6.355733 0.02387244

회귀 결과는 정확히 동일합니다.

보너스: detach() 및 search()를 사용하세요.

search() 함수를 사용하여 현재 R 환경에 연결된 모든 개체를 표시할 수 있습니다.

 #show all attached objects
search()

 [1] ".GlobalEnv" "df" "package:stats"    
 [4] "package:graphics" "package:grDevices" "package:utils"    
 [7] "package:datasets" "package:methods" "Autoloads"        
[10] "package:base"  

그리고 detach() 함수를 사용하여 현재 분리된 객체를 분리할 수 있습니다.

 #detach data frame
detach(df)

추가 리소스

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

R에서 환경을 지우는 방법
RStudio에서 모든 플롯을 지우는 방법
R에서 같은 줄에 여러 변수를 인쇄하는 방법

의견을 추가하다

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