Review
# 내장 데이터 iris3 불러오기
data(iris3)
# iris3의 데이터 구조 파악하기
str(iris3)
# iris3의 세 번째 페이지의 행의 수 구하기
nrow(iris[,,3])
# iris3의 세 번째 페이지의 변수 Sepal L.의 분산 구하기
var(iris3[,"Sepal L.",3])
# 값 "A", "B", "C"를 중복 허락하여 iris3의 세 번째 페이지의 행의 수만큼 추출한 벡터 label 생성하기
label = sample(c("A", "B", "C")nrow(iri3[,,3]), replace = True)
외부 데이터 불러오기
read.csv(file, header = TRUE, ..)
read_excel(path, col_names = TRUE, ...)
read_xls()
read_xlsx()
# readxl 패키지에 포함된 함수들은 패키지 설치가 필요함.
install.packages("readxl")
library(readxl)
csv 파일로 불러오는걸 선호하기 때문에 csv파일로 불러오는 걸 공부하겠음.
excel
### install readxl ----
install.packages("readxl")
library(readxl)
### loading excel ----
read_xlsx("C:\\Users\\user\\OneDrive - 경북대학교\\통계학과\\1-2\\R프로그래밍 및 실험\\w5_1 covid19_psyco.xlsx")
read_xlsx("C:\\Users\\user\\OneDrive - 경북대학교\\통계학과\\1-2\\R프로그래밍 및 실험\\w5_1 covid19_psyco.xlsx", col_names = T)
readxl:: read_excel("C:\\Users\\user\\OneDrive - 경북대학교\\통계학과\\1-2\\R프로그래밍 및 실험\\w5_1 covid19_psyco.xlsx", sheet = 2)
readxl:: read_excel("C:\\Users\\user\\OneDrive - 경북대학교\\통계학과\\1-2\\R프로그래밍 및 실험\\w5_1 covid19_psyco.xlsx", na = "NA")
readxl:: read_excel("C:\\Users\\user\\OneDrive - 경북대학교\\통계학과\\1-2\\R프로그래밍 및 실험\\w5_1 covid19_psyco.xlsx", na = "7")
csv 파일로 불러오는걸 선호하기 때문에 csv파일로 불러오는 걸 공부하겠음.
csv
setwd("C:\\Users\\user\\OneDrive - 경북대학교\\통계학과\\1-2\\R프로그래밍 및 실험")
# 내가 어디 폴더에서 파일을 가지고 작업을 수행할지 정해줌.
# 자기 파일 클릭하고 우클릭하면 속성이 있는데 거기서 파일이 어딨는지 정보가 있으니
# 그걸 복사 붙여넣기하면 됨.
# 근데 처음에 복사하면 \ 가 한 개만 나오는데
# \를 \\이렇게 만들어줘야함.
temp = read.csv("w5_1 covid19_psyco.csv", header =FALSE)
# 파일 불러오기
# header는 column_names를 변수로 쓸건지 아닌지 FALSE는 안 쓴다는거
str(temp)
head(temp, n = 5)
tail(temp)
temp$X ; temp$travel.work
unique(temp$age)
10 %in% temp$time_dp
5:10 %in% temp$time_dp
5:10 %in% head(temp$time_dp)
# temp에서 temp$X, temp$travel.work 열을 제거한 데이터 프레임 example 생성하기
example = temp[, -c(20,22)]
example = temp[, !(names(temp) %in% c("X", "travel.work"))]
example = subset(temp, select = -c(X, travel.work))
EDA
summary(example)
table(example$prefer)
table(example$age, example$prefer)
hist(example$time_bp)
hist(example$home_env)
example$certaindays_hw = as.factor(example$certaindays_hw)
str(example)
Practice1
# temp의 변수 age 내 오타를 수정하고 확인
temp[temp$age == "Dec-18"] == "12-18"
# na개수
sum(is.na(temp$X))
sum(is.na(temp$travel.work))
# na개수와 temp의 행의 수가 같은지 확인
sum(is.na(temp$X)) == nrow(temp)
sum(is.na(temp$travel.work)) == nrow(temp)
Practice2
names(temp)
# 를 통해서 X와 travel.work이 column의 몇 번째인지 알아보기
example = temp[,-c(20,22)]
example = temp[,!(names(temp) %in% c("X", "travel.work")]
exmaple = subset(temp, select = -c(X, travel.work))
# subset(x, select,...)
## x : object to be subsetted
## select : expression, indicating columns to select from a dataframe
### 여기서 select 안에 있는 column의 변수들은 "" 표시 X
파일 내보내기
setwd("C:\\Users\\user\\OneDrive - 경북대학교\\통계학과\\1-2\\R프로그래밍 및 실험")
result = table(example$age, example$prefer)
# age가 행 부분이 되고, prefer이 열 부분이 됨.
write.csv(result, file = "table.csv")
# result라는 데이터 프레임을 csv로 저장
write.csv(table(example$age, example$prefer), file = "table2.csv")
write.csv(example[1:3, 1:4], file = "dataframe.csv")
# example의 1부터 3부분의 행과 1부터 4의 열을 추출해서 csv 파일로 만들고 파일 이름은 dataframe.csv
리스트 저장하기
write.csv(list(a = example[1:10, 1:4], b = 1:10),
file = "list1.csv")
이런 식으로 저장됨.
write.csv(list(a = example[1:10, 1:4], b = 1:5),
file = "list2.csv")
1번째 데이터 프레임과 2번째 데이터 프레임의 F열 값이 다르다는 것을 확인할 수 있음.
이게 왜냐면
write.csv(list(a = example[1:10, 1:4], b = 1:10),
file = "list1.csv")
write.csv(list(a = example[1:10, 1:4], b = 1:5),
file = "list2.csv")
10개의 행을 불러오는건 둘 다 같은데, b의 값이 1부터 10까지인거랑 b가 1부터 5까지인 것에서 차이가 난다는 걸 확인할 수 있음.
다른 방법
erer::write.list(list(a = example[1:3,1:4], b = 1:10), file = "list_.csv") # a가 행으로 들어감.
.rdata
### rdata
setwd("C:\\Users\\user\\OneDrive - 경북대학교\\통계학과\\1-2\\R프로그래밍 및 실험")
save(result, file = "rda file.rda")
# save(result, file = "rda file.rdata")
# R의 고유한 저장형식
# 현재까지 작업한 환경을 현 작업공간(working directory)에 저장함.
save.image(file = "image.rda")
# 현재 작업 중인 공간 전체를 저장
load("image.rda")
load("rda file.rda")
# "로드"는 외부 파일에 저장된 데이터나 객체를 R 프로그램에서 사용할 수 있도록 가져오는 과정
load의 사용
기존의 global Environment는 이런 상태임.
그런데
load("image.rda")
해주면
이렇게 생김.
전에 있던 파일의 저장된 데이터와 객체를 가져와줄 수 있도록 함.
'프로그래밍 > R프로그래밍' 카테고리의 다른 글
R 프로그래밍 - 데이터 구조 (array, list, data.frame) (1) | 2023.10.22 |
---|---|
R 프로그래밍 - 데이터 구조 (vector, matrix, factor) (0) | 2023.10.22 |
R 프로그래밍 - 변수 종류 (1) | 2023.10.22 |
R 프로그래밍 - data merge (1) | 2023.10.18 |
R 프로그래밍 - dataset (0) | 2023.10.16 |