'분석결과 Console 내용 text로 저장하기'에 해당되는 글 1건

  1. 2015.09.17 ggplot2 저장 : ggsave(), console 내용 text 저장 : capture.output()

한두개 정도 일회성으로 그래프 그리고 말거면 그냥 화면 캡쳐하는 프로그램 사용하거나 아니면 RStudio의 파일 내보내기를 사용하면 됩니다. 

 

한두번 분석하고 말거면 그냥 마우스로 Console 창 분석결과에 블럭 설정하고 Copy & Paste 하면 됩니다.

 

하지만, 수백개, 수천개의 그래프를 그리고 이를 파일로 저장해야 하고 자동화(사용자 정의 함수, 루프) 해야 한다거나, 분석이나 모형개발을 수백개, 수천개 해야 하고 이의 결과를 따로 저장해야 한다면 이걸 수작업으로 매번 할 수는 없는 노릇입니다.  시간도 많이 걸리고, 아무래도 사람 손이 자꾸 타다 보면 실수도 하기 마련이기 때문입니다. 

 

이에 이번 포스팅에서는

 

(1) ggplot2로 그린 그래프를 jpg 나 pdf 파일로 저장하는 방법

     : ggsave() 

 

(2) Console 창에 나타나는 분석 결과, 모형 개발 결과를 text 파일로 저장하는 방법

     : capture.output()

 

에 대해서 소개하겠습니다.  R script로 위 작업을 수행할 수 있다면 프로그래밍을 통해 자동화도 할 수 있겠지요.

 

 

예제로 사용할 데이터는 MASS 패키지 내 Cars93 데이터프레임의 고속도로연비(MPG.highway), 무게(Weight), 엔진크기(EngineSize), 마련(Horsepower), 길이(Length), 폭(Width) 등의 변수를 사용해서 선형 회귀모형을 만들고 이의 적합 결과를 text 파일로 내보내기를 해보겠습니다.

 

 
> # dataset : Cars93 dataframe,  Weight, MPG.highway variable
> library(MASS)
> str(Cars93)
'data.frame':	93 obs. of  27 variables:
 $ Manufacturer      : Factor w/ 32 levels "Acura","Audi",..: 1 1 2 2 3 4 4 4 4 5 ...
 $ Model             : Factor w/ 93 levels "100","190E","240",..: 49 56 9 1 6 24 54 74 73 35 ...
 $ Type              : Factor w/ 6 levels "Compact","Large",..: 4 3 1 3 3 3 2 2 3 2 ...
 $ Min.Price         : num  12.9 29.2 25.9 30.8 23.7 14.2 19.9 22.6 26.3 33 ...
 $ Price             : num  15.9 33.9 29.1 37.7 30 15.7 20.8 23.7 26.3 34.7 ...
 $ Max.Price         : num  18.8 38.7 32.3 44.6 36.2 17.3 21.7 24.9 26.3 36.3 ...
 $ MPG.city          : int  25 18 20 19 22 22 19 16 19 16 ...
 $ MPG.highway       : int  31 25 26 26 30 31 28 25 27 25 ...
 $ AirBags           : Factor w/ 3 levels "Driver & Passenger",..: 3 1 2 1 2 2 2 2 2 2 ...
 $ DriveTrain        : Factor w/ 3 levels "4WD","Front",..: 2 2 2 2 3 2 2 3 2 2 ...
 $ Cylinders         : Factor w/ 6 levels "3","4","5","6",..: 2 4 4 4 2 2 4 4 4 5 ...
 $ EngineSize        : num  1.8 3.2 2.8 2.8 3.5 2.2 3.8 5.7 3.8 4.9 ...
 $ Horsepower        : int  140 200 172 172 208 110 170 180 170 200 ...
 $ RPM               : int  6300 5500 5500 5500 5700 5200 4800 4000 4800 4100 ...
 $ Rev.per.mile      : int  2890 2335 2280 2535 2545 2565 1570 1320 1690 1510 ...
 $ Man.trans.avail   : Factor w/ 2 levels "No","Yes": 2 2 2 2 2 1 1 1 1 1 ...
 $ Fuel.tank.capacity: num  13.2 18 16.9 21.1 21.1 16.4 18 23 18.8 18 ...
 $ Passengers        : int  5 5 5 6 4 6 6 6 5 6 ...
 $ Length            : int  177 195 180 193 186 189 200 216 198 206 ...
 $ Wheelbase         : int  102 115 102 106 109 105 111 116 108 114 ...
 $ Width             : int  68 71 67 70 69 69 74 78 73 73 ...
 $ Turn.circle       : int  37 38 37 37 39 41 42 45 41 43 ...
 $ Rear.seat.room    : num  26.5 30 28 31 27 28 30.5 30.5 26.5 35 ...
 $ Luggage.room      : int  11 15 14 17 13 16 17 21 14 18 ...
 $ Weight            : int  2705 3560 3375 3405 3640 2880 3470 4105 3495 3620 ...
 $ Origin            : Factor w/ 2 levels "USA","non-USA": 2 2 2 2 2 1 1 1 1 1 ...
 $ Make              : Factor w/ 93 levels "Acura Integra",..: 1 2 4 3 5 6 7 9 8 10 ...

 

 

 

 

고속도로연비(PMG.highway)와 차 무게(Weight) 간의 산포도를 ggplot으로 그리면 아래와 같이 RStudio 우측 하단의 Plot 창에 그래프가 생성됩니다.

 

 

> # Scatter Plot of Weight & MPG.highway
> library(ggplot2)
> 
> ggplot(Cars93, aes(x=Weight, y=MPG.highway)) +
+   geom_point(shape=19, size=3, colour="blue") +
+   ggtitle("Scatter Plot of Weight & MPG.highway")
 

 

 

 

 

이를 ggsave() 함수를 사용해서 jpg 파일로 저장해서 내보내기를 해보겠습니다.  pdf 파일로 저장하려면 jpg 대신에 pdf 를 사용하면 됩니다.

 

 

> # saving ggplot with jpg format file : ggsave() > ggsave(file="C:/Users/user/Documents/R/scatter_plot.jpg", # directory, filename + width=20, height=15, units=c("cm")) # width, height, units

 

 

 

 

 

단순 선형회귀모형과 다변량 선형회귀모형을 각각 적합시켜보면 아래와 같습니다.

 

 
> # linear regression modeling
> fit_1 <- lm(MPG.highway ~ Weight, Cars93)
> summary(fit_1)

Call:
lm(formula = MPG.highway ~ Weight, data = Cars93)

Residuals:
    Min      1Q  Median      3Q     Max 
-7.6501 -1.8359 -0.0774  1.8235 11.6172 

Coefficients:
              Estimate Std. Error t value Pr(>|t|)    
(Intercept) 51.6013654  1.7355498   29.73   <2e-16 ***
Weight      -0.0073271  0.0005548  -13.21   <2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 3.139 on 91 degrees of freedom
Multiple R-squared:  0.6572,	Adjusted R-squared:  0.6534 
F-statistic: 174.4 on 1 and 91 DF,  p-value: < 2.2e-16

> 
> 
> fit_2 <- lm(MPG.highway ~ Weight + EngineSize + Horsepower + Length + Width, Cars93)
> fit_3=stepAIC(fit_2, direction="both")
Start:  AIC=210.77
MPG.highway ~ Weight + EngineSize + Horsepower + Length + Width

             Df Sum of Sq     RSS    AIC
- Horsepower  1      1.38  789.67 208.93
- EngineSize  1      2.62  790.91 209.07
- Width       1      7.03  795.33 209.59
<none>                     788.30 210.77
- Length      1     44.23  832.53 213.84
- Weight      1    562.35 1350.65 258.84

Step:  AIC=208.93
MPG.highway ~ Weight + EngineSize + Length + Width

             Df Sum of Sq     RSS    AIC
- EngineSize  1      1.62  791.29 207.12
- Width       1      7.95  797.62 207.86
<none>                     789.67 208.93
+ Horsepower  1      1.38  788.30 210.77
- Length      1     48.74  838.41 212.50
- Weight      1    699.19 1488.87 265.90

Step:  AIC=207.12
MPG.highway ~ Weight + Length + Width

             Df Sum of Sq     RSS    AIC
- Width       1     13.71  805.00 206.72
<none>                     791.29 207.12
+ EngineSize  1      1.62  789.67 208.93
+ Horsepower  1      0.38  790.91 209.07
- Length      1     52.31  843.61 211.07
- Weight      1    749.41 1540.70 267.09

Step:  AIC=206.72
MPG.highway ~ Weight + Length

             Df Sum of Sq     RSS    AIC
<none>                     805.00 206.72
+ Width       1     13.71  791.29 207.12
+ EngineSize  1      7.38  797.62 207.86
+ Horsepower  1      0.21  804.79 208.69
- Length      1     91.62  896.62 214.74
- Weight      1   1039.48 1844.48 281.82
> summary(fit_3)

Call:
lm(formula = MPG.highway ~ Weight + Length, data = Cars93)

Residuals:
    Min      1Q  Median      3Q     Max 
-7.0988 -1.8630 -0.2093  1.4199 11.3613 

Coefficients:
              Estimate Std. Error t value Pr(>|t|)    
(Intercept) 37.5217809  4.6998055   7.984 4.41e-12 ***
Weight      -0.0096328  0.0008936 -10.780  < 2e-16 ***
Length       0.1155263  0.0360972   3.200   0.0019 ** 
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 2.991 on 90 degrees of freedom
Multiple R-squared:  0.6922,	Adjusted R-squared:  0.6854 
F-statistic: 101.2 on 2 and 90 DF,  p-value: < 2.2e-16

 

 

 

 

이를 capture.output() 함수를 사용하여 text 파일로 내보내서 차곡 차곡 쌓아가면서 저장하는 방법은 아래와 같습니다.  결과 text 파일을 화면캡채해서 같이 올립니다. 

 

> 
> # capture.output()
> # (1) Simple Linear Regression Model (y=MPG.highway, x=Weight)
> cat("\n", 
+     "\n",
+     "==============================================================", "\n", 
+     " [ Simple Linear Regression Model (y=MPG.highway, x=Weight)]  ", "\n", 
+     "==============================================================", "\n", 
+     file="C:/Users/user/Documents/R/lm_MPG_highway.txt", append = TRUE)
> 
> capture.output(summary(fit_1), 
+                file="C:/Users/user/Documents/R/lm_MPG_highway.txt", append = TRUE)
> 
> 
> # (2) Multivariate Linear Regression Model (y=MPG.highway, x1~x5)
> cat("\n", 
+     "\n",
+     "===============================================================", "\n", 
+     " [ Multivariate Linear Regression Model (y=MPG.highway, x1~x5)]  ", "\n", 
+     "===============================================================", "\n", 
+     file="C:/Users/user/Documents/R/lm_MPG_highway.txt", append = TRUE)
> 
> capture.output(summary(fit_3), 
+                file="C:/Users/user/Documents/R/lm_MPG_highway.txt", append = TRUE)

 

 

 

 

 

 

 

 

노가다 하기 싫다면 프로그래밍하고 자동화하는 것이 정답이지요. 

위의 작업을 반복해야 한다면 사용자 정의 함수를 덧붙여서 파일 경로 끝 부분에 파일 이름 부분을 paste() 함수를 써서 사용자 정의 함수에 입력한 값으로 매 루프 돌때 마다 바꿔치기 될 수 있도록 프로그래밍을 해주면 되겠습니다.

 

많은 도움 되었기를 바랍니다.

 

이번 포스팅이 도움이 되었다면 아래의 '공감 ~♡' 단추를 꾸욱 눌러주세요.^^

 

 

728x90
반응형
Posted by Rfriend
,