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)

+ Recent posts