빅데이터 방법론

What is Computational Social Science?

  1. Lazer D. et al. (2009) “Computational Social Science”, Science.

    • digital traces -> pictures of indivdual and group behavior

    • one-time, self-reported data -> moment-by-moment, unobtrusive observation

    • possible questions:

      • Can the diversity of news and content we receive predict our power or performance?
      • In what ways do societal-level communication patterns affect public health?
    • Barriers

      • Vast, emerging data sets on how people interact offer new perspectives on collective human behavior, but our current paradigms may not be receptive.
      • institutional gaps b/w social science and data science
      • data access and privacy
      • lack of computationally literate social scientists
  2. Wallach H. (2018) “Computational Social Science != Computer Science + Social Data”, Communications of the ACM.

    • computational social science = the study of social phenomena using digitized information and computational & statistical methods

    • how much uncivil activity on YouTube is caused by the content of the video clip versus its source?

    • goals: prediction vs. explanation

    • models: black box to replace human interpretation vs. causal explanation to inform or guide human reasoning

    • data: large-scale, digitized dataset vs. small-scale, pre-designed dataset

    • challenges: black-box predictive models reinforce existing structural biases and marginalize historically disadvantaged populations

  3. Grimmer J. (2015) “We Are All Social Scientists Now: How Big Data, Machine Learning, and Causal Inference Work Together” PS: Political Science & Politics.

    • large-scale data vs. selection, measurement error, and other sources of bias

    • description vs. causal inference (explaining why)

    • careful research design for causal inference: conditions (assumptions) to be met

      • correlation does not imply causality
    • desciptive inferences using big data

      • how some of the fastest growing demographic groups (e.g., biracial Americans) reconcile their competing social and political identities (Davenport 2014).
      • Aggregated newspaper articles can provide unprecedented accounts of the media’s agenda (Boydstun 2013)
      • Online discussions can answer broad questions about how often the public talks about politics during daily life
    • machine-learning algorithms to measure a cerain latent quantity in the world; a suite of methods for validating latent measures needed

    • large-scale datasets for matching wherein the multitude of units ensures that the matches are close or that the treatment and control units are similar (Monroe et al. 2015)

      • from coarse treatments estimated at the population level to more granular treatments in more specific populations
Large amounts of data will not overcome the selection problems that make causal inference so difficult

Causal Inference and Selection Bias

Why causal inference?

  1. Simple correlation does not imply causality
  2. Among many different factors, important to choose the most significant cause

Some facts

  1. 한국은 코로나 바이러스 방역에 잘 대처하는 국가 중 하나이다.

  2. 한국은 세계 유일의 분단 국가이다.

  3. 한국은 일인당 마늘 섭취량이 가장 많은 국가 중 하나이다.

인과관계 추론

  1. 한국은 세계 유일의 분단 국가이기 때문에 코로나 바이러스 방역에 잘 대처한다.

  2. 한국은 일인당 마늘 섭취량이 많기 때문에 코로나 바이러스 방역에 잘 대처한다.

다양한 요인들

  1. 문맹률 (교육 수준)

  2. 중앙집권적 권력 관계와 정보 흐름

  3. 사회적 자본 (연결망)

유의미한 원인을 발견하기 위한 추론

What is the impact of an intervention (X) on an outcome (Y)

  1. Hard to evaluate
  2. Need to compute counterfactuals
  3. Challenge: same person cannot both get treatment and not get treatment

Computing counterfactuals

The treated group and the counterfactual group should have identical characteristics on average, except for benefiting from the intervention -> only reason for different outcomes between treatment and counterfactual is the intervention

Wrong counterfactuals

  1. Before and After: Effect of treatment and time-varying variables on outcome cannot be separated

  2. Compare participants to non-participants (a poor counterfactual) at the same time

Barriers to causal inference

  1. Sample selection
    • Public opinion on Twitter
    • 대학생 상대 설문조사
  2. Omitted variables: spurious correlation by confounding variable
    • TV watching <-> Social capital
    • TV watching <-> Wealth <-> Social capital

질문

  1. 본인의 연구 관심/주제?

  2. 인과관계 추론

  3. 연구대상 선택에서의 편향 발생 가능성?

R Basics

What is R?

- R is a free software environment for statistical computing and graphics. 
- R is a high-level programming language: A set of predefined instructions that a computer is able to understand and react to.

Why R?

- As a user-friendly environment, RStudio has many added values.
- Open source inside
- Plugin ready: CRAN
- Data visualization friendly

How to use R

Foundational notions of R language

  1. Vectors
Vectors

Vectors

  - Numeric
  - Logical / Boolean
  - Character

“object-oriented programming language”

apple <- c(2020123456, 20197890123, 2020456789)
sales <- c("apple", "banana", "kiwi", "melon")
sales
## [1] "apple"  "banana" "kiwi"   "melon"
sales <- c(sales, apple)
sales
## [1] "apple"       "banana"      "kiwi"        "melon"       "2020123456" 
## [6] "20197890123" "2020456789"
  1. Lists

    Containers of objects

my_list <- list(apple, sales)

class(my_list)
## [1] "list"
  - Creating lists
  - Subsetting lists
  1. Data frames

    • All components are vectors, no matter whether logical, numerical, or character
    • All vectors must be of the same length
Data frames

Data frames

  1. Packages
library(tidyverse)
  - Select and show a column of a data frame
  - Add a new column
  1. Functions
Function

Function

  - Ways of manipulating vectors, lists, and data frames
adding_two <- function(x){
  x+2
}
adding_two(x=3)
## [1] 5
my_func <- function(x){
  function_result <- x / 2
}

my_func <- function(x){
  function_result <- x / 2
  return(function_result)
}
a <- 2

my_func <- function(x){
  function_result <- x / 2 + a
  return(function_result)
}

my_func(10)
## [1] 7

R에서 프로젝트 사용하기

RStudio 프로젝트를 사용하면 작업 결과와 데이터를 쉽게 관리 할 수 있습니다.

프로젝트 만들기

RStudio 프로젝트는 R 작업 디렉토리와 연결됩니다. RStudio 프로젝트를 다음과 같은 곳에 만들 수 있습니다.

  • 새로운 디렉토리에서
  • 또는 이미 R 코드 및 데이터가 있는 기존 디렉토리에서 만들 수 있습니다.

새로운 프로젝트를 만들 때, R studio는 :

  1. 프로젝트 디렉토리에 (.Rproj 확장자를 가진) 프로젝트 파일을 생성합니다. 이 파일에는 다양한 프로젝트 옵션이 있고 프로젝트를 직접 여는 지름길로 파일을 사용합니다.
  2. 원본 문서와 창 상태가 저장된 숨겨진 디렉토리를 만듭니다.
  3. 프로젝트를 저장하고 툴바에 프로젝트 이름을 나타냅니다.

프로젝트 열기

  1. Open Project 명령어를 사용하여 기존 프로젝트 파일(예: R.Rproj)을 찾아 선택합니다.
  2. 또는 최근 열었던 프로젝트 목록에서 프로젝트를 선택합니다.

프로젝트 종료하기

프로젝트를 종료하거나 다른 프로젝트를 열면 다음 작업이 실행됩니다. :

  • .RData 및/또는 .Rhistory 는 프로젝트 디렉토리에 기록됩니다.
  • 오픈 소스 문서(.R 확장 문서) 목록이 저장됩니다. (다음 번에 프로젝트를 열 때, 복원할 수 있습니다.)

Global 옵션 확인

작업 내용이 올바르게 저장되도록 global 옵션을 확인해 봅시다.

  • Restore .RData into workspace at startup - 시작 시, R 작업 공간(전역 환경) 안에 초기 작업 디렉토리에 있는 .RData 파일(있는 경우)을 저장하세요.
  • Save workspace to .RData on exit - 종료 시, .RData를 저장할지 여부를 묻고 항상 저장하거나 저장하지 않습니다.
  • Always save history (even when not saving .RData) - 종료할 때, .RData 파일을 저장하지 않기로 선택하더라도 세션의 명령을 사용하여 .Rhistory 파일이 항상 저장되는지 확인하세요.

R 패키지

R을 사용하여 텍스트 마이닝 분석을 할 경우 관련 패키지를 설치하면 텍스트 끌어오기, 전처리와 분석은 물론 결과의 시각화 작업을 보다 편리하고 효율적으로 수행할 수 있다.

패키지? 라이브러리?

R은 오픈 소스 소프트웨어로서 웹 스크래핑&크롤링에 특화되어있는 기능들을 잘 활용하는 것이 중요하다.

패키지는 R의 함수들이 목적에 따라 모여있는 집합체를 말한다.

라이브러리는 패키지를 다운로드 받은 장소를 말한다. 저장된 패키지를 R에 설치함으로서 우리는 포함되어 있는 함수들을 활용할 수 있게 된다. 그렇다면, R에서 어떻게 패키지를 다운로드 받고 설치할 수 있을까?

가령, 우리가 텍스트를 분석하기 위해 필요한 함수들이 “stringr”, “pdftools”, 그리고 “wordcloud”라는 패키지에 포함되어 있다고 가정해보자. 패키지들을 다운로드 받기위해서는 다음의 코드를 실행해야 한다.

install.packages("pdftools")

install.packages("stringr")

install.packages("wordcloud")

특히, install.packages라는 함수 뒤에 괄호가 따라오게 되는데, 이 괄호 안에 패키지의 이름이 입력된다. 주의점: 패키지의 이름은 문자 코드이기 때문에 따옴표를 붙여줘야 한다.

위의 정보를 입력하면 R은 해당 패키지를 CRAN이라는 서버로부터 다운로드 받는다. 하지만 패키지를 다운로드 받았을 뿐, 해당 함수를 실행하기 위해서 패키지를 R 세션에 “로드”해야하는 과정이 필요하다. 이 작업은 library()라는 함수로 실행한다.

library(pdftools)
## Using poppler version 0.73.0
library(stringr)
library(wordcloud)
## Loading required package: RColorBrewer

이러한 과정을 거치게 되면 우리는 오늘 R에서의 텍스트 분석을 위한 패키지 설치를 완료하게 된다: 1) pdftools는 pdf 파일을 R로 불러올때 필요한 함수를 제공한다; 2) stringr은 불러온 파일로부터 추출한 텍스트를 분석을 위해 전처리하는 과정에서 필요한 함수를 제공한다; 3) wordcloud는 전처리 후 분석한 결과를 시각화 하는데 필요한 함수를 제공한다.

디렉토리란?

텍스트를 분석하기 위해 다운로드 받은 디지털 문서가 저장되어 있는 장소를 알아야 R로 파일을 불러올 수 있다. 이때 필요한 정보가 Working Directory이다. 이 폴더는 R session에서 작업하는 파일들의 주소로서 다음의 함수를 이용하면 알 수 있다.

getwd() # 현재 작업중인 디렉토리 찾기 (입력 및 출력값이 저장되는 장소)
## [1] "/Users/shinlee/Dropbox/2020_Class/fall/big data methodology/R"