본문 바로가기
수업(국비지원)/R

[R] matrix, dataframe

by byeolsub 2023. 4. 21.

📌

###### matrix를 이용하여 햄버거 영양 데이터 분석

#byrow=T : 행우선으로 데이터 설정
burger <- matrix(c(514,917,11,533,853,13,566,888,10),nrow=3,byrow=T)
burger

#행과 열의 이름 지정
rownames(burger)<-c('M','L','B') #행의 이름 지정
colnames(burger)<-c('kcal','na','fat') #열의 이름 지정

#M사의 나트륨 함량 조회
burger['M','na'] #matrix[행,열]

#M사의 데이터 조회
burger['M',] #matrix[행,] 

#모든회사의 kcal데이터를 조회
burger[,'kcal'] #matrix[,열]

###### dataframe을 이용한 햄버거 영양 성분 분석
kcal <- c(514,533,566)
na <- c(917,853,888)
fat <- c(11,13,10)
menu <- c('새우','불고기','치킨')
burger <- data.frame(kcal,na,fat,menu)
burger

#행의 이름 설정
rownames(burger) <- c('M','L','B')
burger

#M사의 na 값 조회
burger['M','na']

#M사의 모든 정보 조회
burger['M',]

#모든 회사의 kcal값 조회
burger[,'kcal']

#'M'사와 'B'사의 menu값 조회
burger[c('M','B'),'menu']  #백터 형태로 데이터 

#'M'사와 'B'사의 menu,kcal값 조회
burger[c('M','B'),c('menu','kcal')]

#R에서 제공해주는 iris 데이터 이용하기
iris

# 어떤 구조로 되어있는지 확인하고 싶을때 사용한다.
head(iris) #처음 6개의 데이터만 출력
tail(iris) #마지막 6개의 데이터만 출력

#행, 열의 갯수
dim(iris) #행열의 갯수
nrow(iris) #행의 갯수
ncol(iris) #열의 갯수
colnames(iris) #열의 이름 조회
str(iris) #dataframe의 데이터 요약 정보

#iris 데이터의 품종만 조회
iris[,'Species'] #컬럼명으로 조회
iris[,5] #컬럼의 순서(인덱스)로 조회 
levels(iris[,5])

#각 품종별 데이터 건수
table(iris[,5])
#5번 컬럼(품종)을 제외하고 조회
iris[,-5]

#5번 컬럼을 제외하고, 열별 합계를 조회
colSums(iris[,-5])

#5번 컬럼을 제외하고, 열별 평균 조회
colMeans(iris[,-5])

#5번 컬럼을 제외하고, 행별 합계 조회
rowMeans(iris[,-5])
#5번 컬럼을 제외하고, 행별 평균 조회
rowMeans(iris[,-5])

#품종이 setosa인 데이터만 iris에 저장하기
iris1 <- subset(iris,Species=='setosa')
iris1
str(iris1)
levels(iris1[,5])

#Sepal.Length >5 이고, Sepal.Width>4인 행만 iris2에 저장하기
iris2 <- subset(iris,Sepal.Length>5 & Sepal.Width>4)
iris2

#열 조회하기
#Sepal.Length >5 이고, Sepal.Width>4인 행의 
#Petal.Length Petal.Width Species 컬럼만 조회하기
iris2[,c(3,4,5)]
iris2[,c('Petal.Length' ,'Petal.Width' ,'Species')]
iris2[,c(3:5)] #c(3:5) : 3~5까지의 숫자값들. 3,4,5
subset(iris,Sepal.Length > 5 & Sepal.Width > 4)[,c(3,4,5)]

sum(iris[,1]) #1열의 합
mean(iris[,1]) #1열의 평균
max(iris[,1]) #1열의 최대값
min(iris[,1]) #1열의 최소값

#iris 데이터의 자료형 
class(iris)
is.data.frame(iris)
is.matrix(iris)

#미국의 주의 정보 : state.x77
state.x77
class(state.x77)
state <- data.frame(state.x77) #data.frmae <- matrix 변환
class(state)

#trees 데이터를 이용한 데이터 추출
trees
#직경의 평균값 구하기
mean(trees[,1])
mean(trees[,'Girth'])
mean(trees$Girth)
str(trees)

#1.직경(Girth)은 화원에서 보유한 벛나무의 평균보다 커야한다.
tree1 <- subset(trees,Girth > mean(trees$Girth))
tree1
nrow(tree1)
#2.높이(Height)는 80보다 커야한다.
#3.부피(Volume)는 50보다 커야한다.
# 3가지를 모두 만족하는 나무의 갯수 출력하기
tree2 <- subset(trees,Girth > mean(trees$Girth) & Height > 80 & Volume >50)
nrow(tree2)

 

###### 종업원의 팁 자료형 분석하기 : reshape2 패키지에 저장된 데이터이다.
tips
#reshape2 패키지 설정하기 - 의존성 주입 같은?
install.packages('reshape2')
library(reshape2) #설정된 패키지 사용하기.
tips
.libPaths() #패키지가 설정된 폴더를 조회하기. 폴더에 한글경로 안됨.
#.libPaths(한글이름이 없는 폴더로 다시 지정) # 패키지 경로 설정

class(tips)
str(tips)
#   total_bill : 전체 결제금액
#   tip        : 팁금액
#   sex        : 성별
#   smoker     : 흡연여부
#   day        : 요일.
#   time       : 점심/저녁
#   size       : 인원수

head(tips)
#요일별 팁을 받은 개수 조회하기
table(tips$day)
table(tips[,5])
table(tips[,"day"])

#시간별 팁을 받은 개수 조회하기
table(tips$time)
table(tips[,6])
table(tips[,"time"])

#시간대 별로 Dinner인 경우만 조회하여 dinner 데이터에 저장하고, 
#Lunch인 경우만 lunch 데이터에 저장하기
dinner <- subset(tips,time=='Dinner')
lunch <- subset(tips,time=='Lunch')
dinner
lunch

#dinner와 lunch 데이터 셋에서 결제금액,팁,인원수의 평균 구하기
#colMeans()
colMeans(dinner[,c(total_bill,tip,size)])
colMeans(dinner[,c(-3,-4,-5,-6)])
colMeans(lunch[,c(total_bill,tip,size)])
colMeans(lunch[,c(-3,-4,-5,-6)])

#결제금액 대비 팁의 비율 조회하기
tips$tip/tips$total_bill
#결제금액 대비 팁의 비율이 높은 값 구하기
max(tips$tip/tips$total_bill)
#결제금액 대비 팁의 비율이 낮은 값 구하기
min(tips$tip/tips$total_bill)
#전체 결제금액 대비 팁의 비율의 평균 조회
mean(tips$tip/tips$total_bill)

#dinner와 lunch 데이터의 팁의 비율의 평균 조회하기
mean(dinner$tip/dinner$total_bill)
mean(lunch$tip/lunch$total_bill)

 

'수업(국비지원) > R' 카테고리의 다른 글

[R] Exam  (0) 2023.04.24
[R] 시각화 - 그래프, 히스토그램, 상자그래프  (0) 2023.04.21
[R] Data Object  (0) 2023.04.21
[R] 산술 연산자와 factor  (0) 2023.04.21