1장 연습문제

1번. 다음은 학생들의 키(cm)와 체중(kg)데이터이다.

#(1) 이를 변수 height와weight 자료로 입력하라
height <- c(163,157,178,190,150,167,183,153,160,172,168)
weight <- c(57,42,67,85,40,55,72,43,55,67,69)
#(2) 각 학생의 BMI 지수를 계산하라. BMI = 체중/키*키 
BMI <- data.frame(BMI = round(weight/(height/100)^2, 2))
BMI
##      BMI
## 1  21.45
## 2  17.04
## 3  21.15
## 4  23.55
## 5  17.78
## 6  19.72
## 7  21.50
## 8  18.37
## 9  21.48
## 10 22.65
## 11 24.45
#(3) height, weight, BMI를 합쳐 physical이란 데이터 프레임을 만들어라.
physical <- data.frame(height, weight, BMI)
physical
##    height weight   BMI
## 1     163     57 21.45
## 2     157     42 17.04
## 3     178     67 21.15
## 4     190     85 23.55
## 5     150     40 17.78
## 6     167     55 19.72
## 7     183     72 21.50
## 8     153     43 18.37
## 9     160     55 21.48
## 10    172     67 22.65
## 11    168     69 24.45
#(4) physical에서 BMI<20인 학생들의 자료를 따로 모아 under 이름의 자료에 저장하라
under <- physical[physical$BMI<20,]
under
##   height weight   BMI
## 2    157     42 17.04
## 5    150     40 17.78
## 6    167     55 19.72
## 8    153     43 18.37
  1. 다음은 이화 중학교 학생들의 공부시간과 성적에 대한 자료이다.
#(1) 공부시간과 성적의 산점도를 그려라
time  <- c(12,13,9,4,4,7,10,3,8,3,5,9,14,10,3,6,6,8,9)
score <- c(97,90,89,85,63,75,80,55,78,42,63,78,88,92,82,72,45,72,80)
ggplot() + geom_point(aes(x=time, y=score)) + theme_bw()

#(2) 공부시간을 독립변수(x)로, 점수를 종속변수(y)로 하는 선형 회귀 직선을 구하라.
reg <- lm(score ~ time)
# y= 51.70701 + 3.101866*x
summary(reg)
## 
## Call:
## lm(formula = score ~ time)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -25.318  -4.369  -1.115   4.876  20.987 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  51.7070     6.5726   7.867 4.58e-07 ***
## time          3.1019     0.7992   3.881   0.0012 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 11.55 on 17 degrees of freedom
## Multiple R-squared:  0.4698, Adjusted R-squared:  0.4386 
## F-statistic: 15.06 on 1 and 17 DF,  p-value: 0.0012
#(3) (1) 산점도 위에 (2)의 선형회귀 직선을 겹쳐 그려라.
ggplot() + 
geom_point (aes(x=time, y=score)) + 
geom_smooth(aes(x=time, y=score), method="lm", se=FALSE)+
theme_bw()

plot(time, score)
abline(lm(score ~ time))

  1. 30명을 대상으로, 이용하고 있는 이동통신사를 조사하니 다음과 같은 결과가 나왔다. 이 자료에 대하여 히스토그램을 그려라.
data <- c("A","A","B","C","B","A","A","A","B","B","C","B","C","A","C","B","A","C","C","B","A","A","B","A","C","B","A","B","B","A")
histogam <- function(data){
  num_3 <- rep(NA, length(data))
  for (i in 1:length(data)){
     if      (data[i]=="A") num_3[i]=1
     else if (data[i]=="B") num_3[i]=2
     else if (data[i]=="C") num_3[i]=3
  }   
  return(num_3)}
num_data <- histogam(data)

  ggplot(NULL, aes(x=num_data))+
    geom_histogram(binwidth =0.5) +
    scale_x_discrete(limit = c("A", "B", "C")) +
    scale_y_continuous(breaks=seq(1, 12, 1)) +
    theme_bw()+ 
    xlab("")