mat1 = matrix(1:20, nr = 5, nc = 4)
mat2 = matrix(-1:-20, nr = 5, nc = 4)
mat0 = matrix(0, nr = 5, nc = 4) # 모든 항을 0으로 만들어줌. 즉, 영행렬을 만들어줌. 
mat1 + mat2 == mat0 # T, 값 하나하나를 지정해서 T를 출력해줌.
mat1 - mat1 == mat0 # T, 값 하나하나를 지정해서 T를 출력해줌.
10*mat1 ; mat1/2 # 항마다 곱해주고 나눠줌.
t(mat1) # transposed matrix(전치행렬) : 대각선을 기준으로 뒤집은 행렬

행렬 A의 덧셈의 역원: -A

항등행렬(I): 대각성분은 모두 1, 나머지 원소는 0인 행렬

 

행렬의 곱셈

AI = IA = A

AB = BA = I  # 이렇게 되면 A의 역원은 B가 됨.

- 항등원 : 이항연산을 했을 때 자기자신이 나오게 만드는 원소 

- 역원: 이항연산을 했을 때 항등원이 나오게 만드는 원소 

- 곱셉에서의 항등원 : 단위 행렬(주 대각선의 원소가 모두 1이며 나머지 원소는 모두 0인 정사각행렬)

- 곱셉에서의 역원 : A^-1

- 행렬의 곱셈을 위해서는 좌측 행렬의 열의 수와 우측 행렬의 행의 수가 같아야 함. 

mat3 = matrix(1:9, nr = 3)
mat4 = matrix(seq(1,2,length=9), nr =3)
mat3 * mat4 # 각 원소에 대응되는 것끼리 곱셈
mat3 %*% mat4 # 행렬의 곱셈
det(mat3); det(mat4)
mat5 = matrix(c(1,2,1:7), nr = 3)
det(mat5)
solve(mat5) # 역행렬

 

역행렬이 존재하는 경우의 해 구하기

# 1
# 3 + 9x = 6
# 5 + 9y = 7
(c(6,7)-c(3,5))/9

# 2
# x + 3y = -2
# 2x + 4y = 3
ex2 = matrix(1:4, nrow=2)
solve(ex2)%*%c(-2,3) # 위의 그림의 논리가 사용된 것
# 곱 방향이 양변이 같아야 함. 
# 그러니깐 우변의 오른쪽에 A^-1이 붙으면 좌변의 오른쪽에 A^-1이 붙어야 함.

행렬 (matrix)

- 동일한 자료형인 원소로 구성된 2차원의 자료 구조 

 

 

 

 

배열 (array)

- matrix의 확장된 형태로 3차원 이상의 배열을 의미

- 동일한 자료형, n 차원 이상

array(<원소가 될 vector>,dim = c(행의 수, 열의 수, 페이지 수))
# 참조
<객체명> [<row_index>, <col_index>, <page_index>]
<객체명> [<row_index>, , ]
<객체명> [, <col_index>, ]
<객체명> [, , <page_index>]
# 예시
# 첫 항이 0이고 끝 항이 10인 길이가 48이 되는 등차수열을 원소로 가지는 3X4X4 배열 arry1
arry1 = array(seq(0, 10, length = 48), dim = c(3,4,4))

arry1[3,2,3]
arry1[3,2, ]
arry1[1, , ]
arry1[ ,3, ]

 

 

 

 

 

리스트(list)

- vector와 같은 선형구조

- 각 원소별로 다양한 형태의 자료를 가질 수 있는 다중자료형

- key와 value가 한 쌍으로 저장되며, list에 있는 자료를 참조할 경우 $를 사용

 

# 리스트 자료형 생성

vec1 = c(1,30,-3)
vec2 = c("apple", "banana", "pear")
vec3 = 1:9
arry = array(1:45, dim = c(3,5,3))
mat = arry[,,1]

l = list(vec1, vec2, vec3, arry, mat)

 

# list 참조

l
l[1] ; str(l[1]) 
# 출력 형태
# List of 1
# $ : num [1:3] 1 30 -3

l[[1]] ; str(l[[1]])
# 출력 형태
#  num [1:3] 1 30 -3

names(l)

여기서 출력형태가 l[1]과 l[[1]] 이 다른 이유는 l은 리스트의 형태인데

l[1]은 리스트에서의 첫 번째 값을 통째로 가져왔다고 하는 것이고

l[[1]]은 리스트에 있는 첫 번째의 값을 껍질을 까서 가져왔다고 하는거라서 출력형태가 다른 것이다. 

 

l = list(v1 = vec1, v2 = vec2, v3 = vec3, arry = arry, mtrx = mat) 
# 리스트의 각 원소에 대한 이름 지정
names(l) 
l
l[1] ; str(l[1]) 
# List of 1
#  $ v1: num [1:3] 1 30 -3 
# $ 옆에 이름이 붙어서 나옴. 
# v1을 참조했다는 뜻 

l[[1]] ; str(l[[1]])
# num [1:3] 1 30 -3

names(l)
l$v1 ; l$arry
names(l) = c("e1", "e2", "e3", "e4", "e5"

 

 

 

 

데이터 프레임(data.frame)

- 행과 열로 구성된 2차원 표

- 열 단위로 서로 다른 자료형의 벡터를 저장할 수 있음.

- 각 열에 해당하는 벡터의 길이가 같음.

- 데이터 프레임 생성할 때 vector 여러개를 저장할 수는 있지만 matrix를 저장을 vector와 같이 하면 자료가 이상해지는 것을 확인할 수 있음.

 

# data.frame의 생성
# vector를 이용

vec1 = c(1,30,-3)
vec2 = c("apple", "banana", "pear")
vec3 = 1:9
arry = array(1:45, dim = c(3,5,3))
mat = arry[,,1]

dat1 = data.frame(num1 = vec1, 
                  chr1 = vec2, 
                  num2 = vec3[1:3] 
                  )
dat1
# data.frame의 생성
# matrix를 이용
dat2 = data.frame(mat)

matrix와 dat2의 차이점 비교

 

dat1의 첫 번째값과 두 번째 값 찾아서 각각 5번씩 출력 

dat3 = dat1[rep(1:2, each = 5),]


참조 

dat1$x1
dat2[1,]
dat2[,3]
names(dat3) = c("v1", "v2", "v3") #데이터 프레임 변수 이름 변경

자료구조 

구분 단일 자료형 다중 자료형 그외
1차원 Vector List Factor
2차원 Matrix Data Frame  
N차원 Array    

 

vector 생성

vec0 = 101
vec1 = c(1, 30, -3)
vec2 = c("banana", "apple", "pear")
vec3 = 1:9
vec4 = seq(1, 10, by = 4) # 1부터 10까지 4씩 더한 벡터
vec5 = seq(1, 100, length = 9) # 1부터 100까지 등간격으로 9개의 원소를 가짐.
vec6 = rep(1:3, times = 3) # 1:3을 3번 반복
vec7 = rep(1:3, each = 3) # 1:3의 원소를 각각 3번씩 반복

 

seq, rep 구분 

seq는 from이랑 to가 있어서 1:10 이렇게 쓰면 안되고, 1, 10 이렇게 처음이랑 끝을 구분해서 써주는 것.

rep는 x라서 다수의 숫자를 출력하고 싶을 때는 벡터로 지정을 해주거나 해야함.

seq(from = 1, to = 1, by = ((to - from)/(length.out - 1)),
    length.out = NULL, along.with = NULL, ...)
    
rep(x, ...)

rep.int(x, times)

rep_len(x, length.out)

 

vector의 참조

> 대괄호 사용 

> <객체 이름> [index number]

> 대괄호 안에 참조할 원소의 위치값을 입력

> index에는 c(), :, seq() 등으로 생성한 벡터도 가능

 

vector의 길이 확인 

> length( name_object )

 

예제

# 벡터의 3,3,3,4,4,4 번째 원소
rep(tmp3[c(3,4)], each = 3)
tmp3[rep(3:4, each =3)]

여기서 첫 번째 줄 코드를 해석하면

tmp3의 3,4 번째 숫자를 가져와서 벡터로 만들어주고, 그 다음에 각각을 3번씩 출력해준다.

두 번째 줄 코드를 해석하면

3과 4 각각을 3번 출력하고 벡터화 시킨 뒤에 tmp3의 c(3,3,3,4,4,4)의 값을 출력해준다. 

 

 

 

 

행렬(matrix)

> 수 또는 다항식 등을 직사각형 모양으로 배열한 것

> 동일한 자료형인 원소로 구성된 2차원의 자료구조

matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE,
       dimnames = NULL)
       
matrix(1:6, nrow =3, ncol =2)

 

matrix의 참조

<name_object>[<row_index>, <col_index>] # 행과 열을 함께 참조
<name_object>[<row_index>, ] # 행 참조	
<name_object>[<row_index>, <col_index>] # 열 참조

 

matrix의 차원 확인

dim(<객체명>)

 

 

예제

mat3 = matrix(seq(10, 120, by = 10), nr =2, nc = 6)
mat3[2,4]
mat3[1,]
mat3[,3]
mat3[1:2,]

 

 

 

factor 

> 범주형 자료를 표현하기 위한 구조

> 자료가 사전에 정의된 유형으로만 분류되는 경우 사용됨.

> '자료의 값'과 '사전에 정의하는 수준(level)'으로 이루어짐.

> 특수한 형태의 vector라고 볼 수 있음. 

> vector와 동일한 방법으로 참조 (대괄호 사용)

 

fac1 = factor(c("AB", "B", "O", "A", "A", "B"), level = c("A", "B", "O", "AB"))

fac2 = factor(c("B", "B", "RH-A", "B", "O", "A"), levels = c("A", "B", "O", "AB"))

fac1
fac2 # if levels factor doesn't perceive value that doesn't define in levels to NA.
# 따라서 RH-A의 값을 Na 값으로 인식함. 

fac1[1:3]
levels(fac1)
levels(fac1) = c(levels(fac1), "????") # levels에 수준을 추가

 

변수 

- 숫자나 문자열 등 하나의 항목에 이름을 붙인 것

- 1개의 변수는 하나의 데이터를 보관할 수 있음.

x1 = 5 ; x2 = 7
x1+x2
y = x2 - x1
ls() # 현재 저장된 변수 리스트 확인
rm(y) ; ls() # y만 삭제 후 변수 리스트 확인
rm(list = ls()) ; ls() # 저장된 변수 모두 삭제 후 변수 리스트 확인

 

변수의 종류 

numeric(수치형)

character(문자형)

logical(논리형)

complex(복소수형)

 

 

저장된 변수의 자료형 확인 

mode(x1) # numeric으로 출력
str(x1) # num 5로 출력
is.numeric(x1) # numeric 외에 자료형 다 가능

 

변수의 자료형 변경

as.numeric(x1) # as.character(x1)

 

# 연습
num1 =  1; char1 = 'a' ; logi1 = T

is.numeric(num1) # T
is.character(logi1) # F
is.logical(char1) # F

as.numeric(logi1) 
as.character(num1) 
as.logical(char1) # NA, character의 경우 logical로 바꿀 수 없음.
# 연습 2

as.numeric("Word")
as.numeric("1235")
as.numeric(TRUE)
as.numeric("TRUE")
as.logical(1)
as.logical(0)
as.logical(123)
as.logical("1")
as.logical(4151124)
as.numeric(F)

TRUE는 0 제외 숫자로 표현되면 1

FALSE는 0

 

 

특수 자료형

- 수학적으로 정의되지 않거나, 무한대를 나타내거나, 결측치를 나타내는 등 특수한 상황에 사용

- NA: 결측값(자리는 있음)

- NULL: 값이 존재하지 않음. (자리조차 없음.)

- NaN: 수학적인 정의가 불가능한 값 (0/0)

- Inf/ -Inf : 무한대 (3/0)

 

 

예시

x1 = c(1,2,NA, 4,5)
x2 = c(1,2,NULL, 4, 5)

is.na(x1)
length(x1)
is.na(x2)
length(x2)

결과에서 알 수 있듯이 x1은 자리가 포함되어있고, x2는 그렇지 않다. 

 

 

 

정리

temp_num = 101
temp_chr = "this is an example"
temp_logi = F
temp_cplx = 1i

is.numeric(temp_num)
is.character(temp_chr)
is.logical(temp_logi)
is.complex(temp_cplx)

as.numeric(temp_logi)

 

write( ) 함수

file_hander = open("output.txt", "wt", encoding = "utf-8")

while True:
    words = input("Enter words >>> ")
    if word.startswith("exit"):
    	break
    
    else:
    	file_handler.write(words)
        
file_hander.close()

입력
파일 확인

 

 

파일에서 한 칸씩 띄워서 넣고 싶을 때

file_hander = open("output_1.txt", 'wt', encoding = "utf-8")

while True:
	words = input("Enter words >>> ")
    if words.startswith("exit"):
    	break
        
    else:
    	file_handler.write(words)
        file_handler.write("\n")
        
file_hander.close()

파일 확인

마지막에 4줄까지 표시가 된 것은 공부를 입력하고 file_handler.write("\n")을 통해 한 줄이 띄워진 것이다. 

 

 

 

writelines() 함수

words_list = \
['안녕하세요.', 'Python', '잘하고 싶은 사람입니다.'] # \는 라인이 길어서 두 줄로 표현했다는 뜻

with open("output.txt", "wt", encoding="utf-8") as fp:
    fp.write("\n".join(words_list)) # join은 리스트를 하나의 문자로 만들어주는데 그것의 연결고리가 \n이 되도록
    fp.flush()

'프로그래밍 > Python' 카테고리의 다른 글

Python - 클래스 생성자  (2) 2023.11.25
Python - 클래스  (1) 2023.11.25
Python - File Encoding, 자동으로 파일 객체 닫기  (2) 2023.10.21
Python - file open 시 오류 처리  (0) 2023.10.21
Python - 파일 입출력  (0) 2023.10.21

data_poem.txt의 파일은 다음과 같이 한글로 저장되어있다.

txt 파일

여기서 파일 오픈 에러가 나는지 확인을 하기 위해 다음과 같은 코드를 실행한다. 

try:
    file_handler = open("data_poem.txt", 'rt')  

    data_string  = file_handler.read()             
    print(data_string)                             

    file_handler.close()

except FileNotFoundError as e:
    print(f"파일 오픈 에러 :{e}")
    
except UnicodeDecodeError as e:
    print(f"파일 오픈 에러 :{e}")

 

이 결과는 cp949로 윈도우에서 지원하는 encoding 체계라서 바꿔주려면

encoding 파라미터를 전달하여 파일이 오픈되도록 해야한다. 

file_handler = open("data_poem.txt", 'rt', encoding='utf-8')

data_string  = file_handler.read()             
print(data_string)                             

file_handler.close()

encoding은 한국어냐 외국어냐 영어냐에 따라서 encoding을 바꿔주면 된다.

한글로 파일을 읽을 때는 encoding = 'utf-8'

 

 

 

자동으로 파일 객체 닫기

with open ( ) as f: 파일 사용 뒤 자동으로 파일 객체를 닫는다.

# with의 코딩 블록을 벗어나는 순간 자동으로 파일 객체를 닫아준다.

with open("data_poem.txt", "rt", encoding = 'utf-8') as fp:
	data_string = fp.read()
    print(data_string)

 

 

 

'프로그래밍 > Python' 카테고리의 다른 글

Python - 클래스  (1) 2023.11.25
Python - 텍스트 파일 출력(쓰기)  (0) 2023.10.21
Python - file open 시 오류 처리  (0) 2023.10.21
Python - 파일 입출력  (0) 2023.10.21
Python - 피보나치 수열  (0) 2023.10.14

file open 시 오류 처리

 

존재하지 않는 파일을 읽고자 한다면 에러가 발생한다.

이럴 때는 open으로 파일을 불러올 때 os모듈을 사용하여 파일 존재 여부를 확인하면 된다.

import os 

file_name = "data_science.txt"

if os.path.exists(file_name):
	
    file_handler = open("data_science.txt", "rt")
    data_string = file_handler.read()
    print(data_string)
    file_handler.close()
    
else:
	print(f"파일 오픈 에러 : {file_name} 파일이 존재하지 않습니다.")

 

또는 try, except 구문을 사용해 오류를 처리해주면 된다.

try:
    file_handler = open("data_poem.txt", 'rt')  

    data_string  = file_handler.read()             
    print(data_string)                             

    file_handler.close()

except FileNotFoundError as e:
    print(f"파일 오픈 에러 :{e}")
    
except UnicodeDecodeError as e:
    print(f"파일 오픈 에러 :{e}")

 

 

'프로그래밍 > Python' 카테고리의 다른 글

Python - 텍스트 파일 출력(쓰기)  (0) 2023.10.21
Python - File Encoding, 자동으로 파일 객체 닫기  (2) 2023.10.21
Python - 파일 입출력  (0) 2023.10.21
Python - 피보나치 수열  (0) 2023.10.14
Python - 재귀함수  (0) 2023.10.14

1. 파일 열기

open("파일명","r",encoding = 'utf-8')
open("파일명","w")

open("sample.txt", "rt") # 파일없으면 error남. 
open("sample.txt", "wt") # 파일없어도 error X. 
# 뒤에 t는 text로 읽고 쓰겠다는 뜻

주피터랩 코드설명: shift + tab

 

파일 열기 모드 (open("파일명", 모드, encoding, .....) 여기서 mode에 들어가는 것들을 말함.)

- 생략 : r과 동일

- r : 읽기 모드, 기본값

- w: 쓰기 모드, 기존에 파일이 있으면 덮어씀.

- r+ : 읽기/ 쓰기 겸용 모드

- a : 쓰기 모드. 기존에 파일이 있으면 이어서 씀. append의 약자

- t : 텍스트 모드. 텍스트 파일을 처리. 기본값

- b: 바이너리 모드. 바이너리 파일(=이진 파일)을 처리

 

 

2. 파일처리 

- 파일에 데이터를 쓰거나 파일로부터 데이터를 읽어옴.

 

3. 파일 닫기

변수명.close()

 

+ 컴퓨터가 파일을 가져오는 과정

CPU > memory > disk

disk  > memory > CPU

자료가 나타나고 저장하는과정

파일을 열었으면 닫아줘야함.

다 읽으면 메모리 낭비가 심할 수 있음.

 

 

 

 

 

텍스트 파일 입력 (읽기)

 

read() : 파일 전체를 읽어 문자열로 return 해줌.

file_example = open("data.txt", 'rt')

data_string = file_example.read()
print(data_string)

file_example.close()

코드 실행 결과

 

readline() : 한 줄을 읽어 문자열로 return

file_example = open("data.txt", 'rt')

line_string = file_example.readline()
print(line_string)

file_example.close()

코드 실행 결과

readlines() : 파일 전체를 읽어 줄 문자열이 원소인 list 형태로 return

file_example = open("data.txt", "rt")

line_list = file_example.readlines()
print(line_list)

file_example.close()

여기서 보면 각각의 원소 뒤에 \n이 붙어있는 것을 확인할 수 있다.

그래서 각각의 원소가 한 줄 띄우고 출력될 것이라는 것을 예상할 수 있는데

실행해보면 다음과 같이 나온다.

# 각각의 원소의 결과값을 알기 위해 실행하는 코드
file_example = open("data.txt", "rt")

line_list = file_example.readlines()

for line in line_list:
	print(line)

file_example.close()

이렇게 출력되는데 이것은 print가 default값으로 \n을 가지기 때문이다.

이걸 해결해주기 위해 다음과 같은 코드를 짤 수 있다. 

 

# 각각의 원소의 결과값을 알기 위해 실행하는 코드
file_example = open("data.txt", "rt")

line_list = file_example.readlines()

for line in line_list:
	line = line.strip("\n")
	print(line)

file_example.close()

 

'프로그래밍 > Python' 카테고리의 다른 글

Python - File Encoding, 자동으로 파일 객체 닫기  (2) 2023.10.21
Python - file open 시 오류 처리  (0) 2023.10.21
Python - 피보나치 수열  (0) 2023.10.14
Python - 재귀함수  (0) 2023.10.14
Python - 모듈, 예외처리  (1) 2023.10.14

Review

example = read.csv("C:\\Users\\user\\OneDrive - 경북대학교\\통계학과\\1-2\\R프로그래밍 및 실험\\w5_1 covid19_psyco.csv")

# example에서 관찰값 200개를 랜덤으로 뽑고 앞 변수(열) 5개만 선택하여 example2로 저장
example2 = head(example[sample(1:nrow(example), 200), 1:5])

# example2의 occupation의 빈도표 
table(example$occupation)

# example2의 gender와 occupation의 분할표를 출력
table(example2$gender, example2$occupation)

# example2의 line_of_work에 포함된 값의 종류 확인
unique(example2$line_of_work)

 

동일한 변수 & 관찰값 추가

- 대용량의 데이터의 경우 추가된 자료만을 불러와 기존 데이터에 덧붙일 수 있음.

 예) 동일한 설문지를 조직 A,B에서 조사한 후 각각 코딩하여 자료가 두 개인 경우

 

vector에 관찰값 추가

vec = c(0,5,10)
vec = c(vec, 15)
vec[5] = 20
vec[c(6,8)] = c(25, 35) # 7번째 값은 지정해주지 않았으므로 NA값을 반환함.

 

matrix에 관찰값 추가

mat = matrix(1:10, nc = 5)
mat[3,] = rep(3,5) # 3행에 추가시켜주려고 했으나 error
rbind(mat, rep(3,5)) # 3행에 추가시켜주는 함수
mat = rbind(mat, rep(3,5))
# rbind 설명
# 벡터와 행렬, 데이터 프레임 요소들의 집합을 열로 묶어줌.

 

Practice

data(iris)
head(iris) ; tail(iris)
unique(iris$Species)

# iris에 새 관찰값 추가하기
rbind(iris, c(3.5, 3.5, 1.3, 0.3, "versicolor"))

# vector형태를 data.frame형태로 바꿔서 rbind 활용
newobs = data.frame(3.5, 3.5, 1.3, 0.3, "versicolor")
names(newobs) = name(iris)
head(rbind(newobs, iris))
str(rbind(newobs, iris))

# 두 개의 행을 가져올 때
newobs2 = data.frame(
			c(3.5, 3.7),
            c(3.5, 3.6),
            c(1.3, 1.4),
            c(0.3, 0.4),
            c("versicolor", "virginica"))
names(newobs2) = names(iris)
rbind(iris, newobs2)

 

변수 추가

예) 동일한 조사집단에 대하여 추가적인 설문 문항이 제작된 경우

 

matrix

mat = matrix(1:10, nr = 5)

cbind(mat, c(1:5)+3) 
cbind(c(1:5)+3, mat) 
cbind(mat, c(1:5)+3, c(1:5)-3) # 순서대로 저장됨.
cbind(c(1:5)+3, mat, c(1:5)-3)
# cbind 설명
# Take a sequence of vector, matrix or data-frame arguments and combine by columns.

 

data.frame

paste("id", 10) # 입력한 2개의 문자를 띄어쓰기써서 붙여주기
paste0("id", 10) # 입력한 2개의 문자를 띄어쓰기없이 붙여주기

example3 = example[sample(1:nrow(example), 10), 1:5] #여기서 example은 전에 썼던 파일 (covid)
new = paste0("id", 1:nrow(example3))

#### add variable(1) ----
cbind(example3, new)
cbind(new, example3)

#### add variable(2) ----
example3$id = new
example3[, c("id", "age", "gender","occupation", "line_of_work", "time_bp")]
example3[,c("age", "id", "gender", "occupation", "line_of_work", "time_bp")]

 

Pracitce

iris_1 = iris[iris$Petal.Length == 3.5,]
# iris_1 = subset(iris, Petal.Length == 3.5)

iris_2 = iris[iris$Petal.Length == 5,]
# iris_2 = subset(iris, Petal.Length == 5)

rbind(iris_1, iris_2)
Length = iris$Petal.Length + iris$Sepal.Length
cbind(iris, Length)

 

데이터 병합

- 데이터 합치기

>>> 기준이 없는 경우 : rbind(행 방향), cbind(열 방향) 

>>> 기준이 있는 경우(기준변수가 있는 경우) : merge

                  기준에 따라 inner join, outer join, left join, right join

 

inner / outer

left    /  right

 

 

예제

df1 = data.frame(
    ID = 1:6,
    group = c(rep("B",3), rep("A",2), "B")
)

df2 = data.frame(ID = 3:7, score =c(31,86,76,83,53))

## merge 사용 ----

# inner join
merge(df1, df2) #merge(df1, df2, by ="ID")

# outer join 
merge(df1, df2, all = TRUE)

# left join
merge(df1, df2, all.x = TRUE)

# right join    
merge(df1, df2, all.y = TRUE)

# 중복되는 변수가 존재하는 경우(값이 완전히 동일)
df3 = data.frame(ID=3:5, score=c(31, 86, 76))
merge(df2, df3, by="ID") # score.x와 score.y가 나옴.
merge(df2, df3, by="ID")[,c("ID","score.x")]

 

Practice 

# mtcars의 자료에 k-번째 관찰값이면 'car_k' 값을 가지는 변수 id를 맨 앞에 추가하여 cars로 저장
cars = cbind(id = paste0("car", nrow(mtcars)), mtcars)

# cars 자료 중에 1~10번째 관찰값을 추출하고 변수 id, mpg, disp만 cars1으로 저장
cars1 = cars[1:10, c("id","mpg","disp")]

# cars 자료 중 '1~5번째 관찰값'과 '6번째 이후 관찰값에 대하여 랜덤으로 추출한 5개의 관찰값'에 대하여 
# 변수 id, mpg, cyl만 cars2로 저장
cars2 = cars[c(1:5, sample(6:nrow(cars), size = 5)), c("id","mpg","disp")]

# 함수 merge를 활용하여 변수 id를 기준으로 cars1, cars2에 대하여 inner join/ left join/ outer join
merge(cars1, cars2, by = "id")
merge(cars1, cars2, by = "id", all.x = TRUE)
merge(cars1, cars2, by = "id", all = TRUE)

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")

해주면

이렇게 생김.

전에 있던 파일의 저장된 데이터와 객체를 가져와줄 수 있도록 함. 

+ Recent posts