# Simple addition and subtraction
10+5
## [1] 15
10-5
## [1] 5
# Creating vectors: A sequence of numbers/integers, characters, Booleans
c(1, 3, 5) # Join elements into a vector
## [1] 1 3 5
1:5 # An integer sequence
## [1] 1 2 3 4 5
seq(1, 5, by=2) # A sequence of integers from 1 to 5, increasing by 2
## [1] 1 3 5
rep(1:5, times=3) # Repeat an integer sequence 1:5 three times
## [1] 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
rep(1:5, each=3) # Repeat each element of an integer sequence 1:5 three times
## [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
# R uses the less than symbol followed by the hyphen(<-) as an assignment operator
a <- 10 # assign 10 to the object 'x'
a*2
## [1] 20
a <- 20
a - 5 # subtract 5 from x
## [1] 15
a <- "R uses the less than symbol followed by the hyphen(<-) as an assignment operator"
a
## [1] "R uses the less than symbol followed by the hyphen(<-) as an assignment operator"
table(unlist(strsplit(a, ' ')))
##
## an as assignment by followed hyphen(<-) less
## 1 1 1 1 1 1 1
## operator R symbol than the uses
## 1 1 1 1 2 1
class <- "text mining"
print(class)
## [1] "text mining"
class = "text mining"
# R is an object-oriented programming language; everything can be assigned to an object
fruits <- c("Apple","Grape","Pear","Apple","Mango","Orange","Mango","Strawberry","Grape","Apple")
sort(fruits) # Return the object, fruits, sorted in alphabetical order for characters
## [1] "Apple" "Apple" "Apple" "Grape" "Grape"
## [6] "Mango" "Mango" "Orange" "Pear" "Strawberry"
table(fruits) # See counts of values (elements)
## fruits
## Apple Grape Mango Orange Pear Strawberry
## 3 2 2 1 1 1
unique(fruits) # See unique values (elements)
## [1] "Apple" "Grape" "Pear" "Mango" "Orange"
## [6] "Strawberry"
# String data can be a character vector
hello <- c("Hello!", "World", "is", "good!")
print(hello)
## [1] "Hello!" "World" "is" "good!"
같은 성격(숫자, 문자 등)을 가진 일련의 요소들로 이뤄진 집합(묶음)
예) 숫자 벡터; 문자 벡터; 논리 벡터
# assign a sequence of numbers to a numeric vector object, vector_numeric
vector_numeric <- c(1:6) # a sequence of numbers from 1 to 6
vector_numeric
## [1] 1 2 3 4 5 6
# assign a sequence of characters to a character vector object, vector_character
vector_character <- c("numeric","character","logical") # characters should be distinguished with quotation marks.
vector_character
## [1] "numeric" "character" "logical"
# assign a sequence of Boolean values, TRUE or FALSE, to a logical vector object, vector_logical
vector_logical <- c(TRUE, FALSE, FALSE, TRUE, T, F) # TRUE/FALSE should be uppercase letters
vector_logical
## [1] TRUE FALSE FALSE TRUE TRUE FALSE
4-1. 벡터 요소 선택하기 ### 위치 순서로 지정
fruits[4] # The fourth element of the vector object, fruits
## [1] "Apple"
fruits[-4] # All but the fourth one
## [1] "Apple" "Grape" "Pear" "Mango" "Orange"
## [6] "Mango" "Strawberry" "Grape" "Apple"
fruits[2:4] # Elements from the second to the fourth ones
## [1] "Grape" "Pear" "Apple"
fruits[-(2:4)] # All elements except the second to the fourth ones
## [1] "Apple" "Mango" "Orange" "Mango" "Strawberry"
## [6] "Grape" "Apple"
fruits[c(1,5)] # Elements the first one and the fifth one
## [1] "Apple" "Mango"
Note that parentheses ( ) follow a certain function and square brakets [ ] select vector elements
Vectors
5-1. 리스트 인덱싱: 객체 요소 선택 리스트의 요소 선택 방법? 두개의 대괄호 쌍으로 리스트의 1차 요소인 벡터 선택 하나의 대괄호 쌍으로 리스트의 2차 요소인 벡터의 요소 선택
fruits
## [1] "Apple" "Grape" "Pear" "Apple" "Mango"
## [6] "Orange" "Mango" "Strawberry" "Grape" "Apple"
hello
## [1] "Hello!" "World" "is" "good!"
list_obj <- list(fruits, hello)
list_obj
## [[1]]
## [1] "Apple" "Grape" "Pear" "Apple" "Mango"
## [6] "Orange" "Mango" "Strawberry" "Grape" "Apple"
##
## [[2]]
## [1] "Hello!" "World" "is" "good!"
복수의 벡터들의 결합으로 이뤄짐. 이때 벡터의 성격(숫자, 문자, 논리 등)은 상관없음. 단, 벡터의 길이는 모두 같아야 함.
Data frames
입력된 객체를 이용해 일련의 연산작업을 거쳐 출력하는 기능으로 사전에 정의된 기호
Function
?c # Get help of a particular function c( )
## starting httpd help server ... done
?strsplit
help.search("split") # Search and return the help files for functions that include a word or phrase
help(package = "stringr") # Find help for a package
Note1: R 운 대문자와 소문자를 다르게 인식
word1 <- "TEXT"
word1
## [1] "TEXT"
word2 <- "Text"
word2
## [1] "Text"
word1 == word2
## [1] FALSE
Note2: 함수는 함수가 적용될 객체를 표시하는 괄호와 함께 사용
tolower(word1)
## [1] "text"
toupper(word2)
## [1] "TEXT"
빅카인즈에서 CSV 형태의 뉴스 데이터를 불러온다.
# 20대 대선 후보 관련 뉴스: 키워드 검색 - "이재명" & "윤석열"
# 중앙지, 방송사
# 후보 선출 이후부터 선거일 전 기간
# 제목/본문에 키워드 포함
# 중복 기사 제거 (분석제외)
# 엑셀파일 다운로드 폴더 확인
getwd()
## [1] "D:/Dropbox/2022_Class/DMBD/DM_BD_R"
# 엑셀파일 불러오기
# install.packages("readxl")
library(readxl)
lee <- read_excel("candidate_lee.xlsx", sheet = 1)
lee
## # A tibble: 12,788 x 19
## `뉴스 식별자` 일자 언론사 기고자 제목 `통합 분류1` `통합 분류2`
## <chr> <chr> <chr> <chr> <chr> <chr> <chr>
## 1 01100101.202203~ 20220~ 경향~ 윤호우 ~ "[논설위원~ 사회>여성 사회>사건_~
## 2 01100701.202203~ 20220~ 세계~ 김주영 "책임 통감~ 정치>선거 정치>국회_~
## 3 01100701.202203~ 20220~ 세계~ <NA> "이재명 “~ 정치>선거 정치>청와대
## 4 08100401.202203~ 20220~ YTN 김태민 "이재명, ~ 정치>선거 <NA>
## 5 08100101.202203~ 20220~ KBS <NA> "[풀영상] ~ 정치>선거 정치>국회_~
## 6 01101101.202203~ 20220~ 한국~ 강유빈 "'잠행 모~ 정치>선거 정치>국회_~
## 7 08100101.202203~ 20220~ KBS 김익태 "대선 D-1,~ 정치>선거 정치>청와대
## 8 01100101.202203~ 20220~ 경향~ 박홍두·~ "이 “통합~ 정치>선거 정치>국회_~
## 9 01100201.202203~ 20220~ 국민~ 안명진 "[포착] 이~ 정치>선거 정치>청와대
## 10 01100701.202203~ 20220~ 세계~ <NA> "이재명, ~ 정치>선거 정치>청와대
## # ... with 12,778 more rows, and 12 more variables: 통합 분류3 <chr>,
## # 사건/사고 분류1 <chr>, 사건/사고 분류2 <chr>, 사건/사고 분류3 <chr>,
## # 인물 <chr>, 위치 <chr>, 기관 <chr>, 키워드 <chr>,
## # 특성추출(가중치순 상위 50개) <chr>, 본문 <chr>, URL <chr>,
## # 분석제외 여부 <lgl>
yoon <- read_excel("candidate_yoon.xlsx", sheet = 1)
yoon
## # A tibble: 16,974 x 19
## `뉴스 식별자` 일자 언론사 기고자 제목 `통합 분류1` `통합 분류2`
## <chr> <chr> <chr> <chr> <chr> <chr> <chr>
## 1 08100401.202203~ 20220~ YTN 계훈희 "윤석열, ~ 정치>선거 정치>국회_~
## 2 08100401.202203~ 20220~ YTN 이경국 "윤석열, ~ 정치>선거 정치>국회_~
## 3 01100901.202203~ 20220~ 중앙~ 이해준.~ "尹, 강남~ 정치>선거 정치>국회_~
## 4 08100401.202203~ 20220~ YTN 이경국 "윤석열, ~ 정치>선거 <NA>
## 5 01100701.202203~ 20220~ 세계~ <NA> "홍준표 \"~ 정치>선거 정치>국회_~
## 6 01100701.202203~ 20220~ 세계~ <NA> "심상정 \"~ 정치>선거 정치>국회_~
## 7 08100101.202203~ 20220~ KBS 임연희 "‘대선 D-~ 정치>선거 지역>제주
## 8 01100101.202203~ 20220~ 경향~ 김상범 ~ "심상정 “~ 정치>선거 정치>국회_~
## 9 01100701.202203~ 20220~ 세계~ <NA> "與 \"尹 '~ 사회>사건_~ 정치>행정_~
## 10 08100101.202203~ 20220~ KBS <NA> "[풀영상] ~ 정치>선거 정치>국회_~
## # ... with 16,964 more rows, and 12 more variables: 통합 분류3 <chr>,
## # 사건/사고 분류1 <chr>, 사건/사고 분류2 <chr>, 사건/사고 분류3 <chr>,
## # 인물 <chr>, 위치 <chr>, 기관 <chr>, 키워드 <chr>,
## # 특성추출(가중치순 상위 50개) <chr>, 본문 <chr>, URL <chr>,
## # 분석제외 여부 <chr>
library(tidyverse)
## -- Attaching packages --------------------------------------- tidyverse 1.3.1 --
## v ggplot2 3.3.5 v purrr 0.3.4
## v tibble 3.1.4 v dplyr 1.0.7
## v tidyr 1.1.3 v stringr 1.4.0
## v readr 2.0.1 v forcats 0.5.1
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
candidate <- bind_rows(lee %>%
mutate(candidate="Lee"),
yoon %>%
mutate(candidate="yoon"))
bind_rows(lee %>% mutate(candidate="Lee"),
yoon %>% mutate(candidate="yoon")) -> candidate