59doit

[ R ]연습문제 (5) 5->6 본문

Q.

[ R ]연습문제 (5) 5->6

yul_S2 2022. 11. 20. 16:31
반응형

 1. reshape2패키지와 iris데이터 셋을 사용하여 다음을 실행하시오.

1) 꽃의 종류(Species)를 기준으로 ‘넓은 형식’을 ‘긴 형식’으로 변경하기

install.packages("reshape2")
library(reshape2)
data(iris)

long <- melt(iris, id=c("Species"), na.rm=TRUE)
long

head(long)
#   Species     variable value
# 1  setosa Sepal.Length   5.1
# 2  setosa Sepal.Length   4.9
# 3  setosa Sepal.Length   4.7
# 4  setosa Sepal.Length   4.6
# 5  setosa Sepal.Length   5.0
# 6  setosa Sepal.Length   5.4

 

 

2) 꽃의 종별로 나머지 4가지 변수의 합계 구하기

dcast<-dcast(long,Species~variable,sum)
dcast
#      Species Sepal.Length Sepal.Width Petal.Length Petal.Width
# 1     setosa        250.3       171.4         73.1        12.3
# 2 versicolor        296.8       138.5        213.0        66.3
# 3  virginica        329.4       148.7        277.6       101.3

 

 

 1. dplyr패키지와 iris데이터 셋을 이용하여 다음을 실행하시

1) iris의 꽃잎의 길이(Petal.Length)컬럼을 대상으로 1.5이상의 값만 필터링하시오

install.packages("dplyr")
library(dplyr)
data(iris)

data1 <- iris %>% filter(Petal.Length >= 1.5)
data1

head(data1)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          4.6         3.1          1.5         0.2  setosa
# 2          5.4         3.9          1.7         0.4  setosa
# 3          5.0         3.4          1.5         0.2  setosa
# 4          4.9         3.1          1.5         0.1  setosa
# 5          5.4         3.7          1.5         0.2  setosa
# 6          4.8         3.4          1.6         0.2  setosa

 

 

2) 1)번의 결과에서 1, 3, 5번 컬럼을 선택하시오

data2 <- data1 %>% select(c(1,3,5))
data2

head(data2)
#   Sepal.Length Petal.Length Species
# 1          4.6          1.5  setosa
# 2          5.4          1.7  setosa
# 3          5.0          1.5  setosa
# 4          4.9          1.5  setosa
# 5          5.4          1.5  setosa
# 6          4.8          1.6  setosa

 

 

3) 2)번의 결과에서 1-3번 컬럼의 값을 뺀 diff 파생변수를 만들고, 앞부분 6개만 출력하 시오

data3 <- data2 %>% mutate(diff=Sepal.Length-Petal.Length)
data3

head(data3$diff)
# [1] 3.1 3.7 3.5 3.4 3.9 3.2

 

 

4) 3)번의 결과에서 꽃의 종(Species)별로 그룹화하여 Sepal.Length와 Petal.Length변수의 평균을 계산하시오.

data4 <- data3 %>% group_by(Species) %>% summarise(Sepal.Length_mean = mean(Sepal.Length),Petal.Length_mean=mean(Petal.Length))
data4

#   Species    Sepal.Length_mean Petal.Length_mean
#   <fct>                  <dbl>             <dbl>
# 1 setosa                  5.11              1.59
# 2 versicolor              5.94              4.26
# 3 virginica               6.59              5.55

 

반응형

'Q.' 카테고리의 다른 글

[ R ] ch 13 연습문제  (0) 2022.11.23
[ R ] 연습문제 (6) 6-> ch7  (0) 2022.11.22
[ R ] 연습문제 (4)  (0) 2022.11.18
[ R ] 연습문제 (1)  (0) 2022.11.16
[ Python - Pandas&Numpy ] 예제 평가(4)  (0) 2022.11.13
Comments