Tools (126)

반응형

Data set



Code


/* Get Age */
data workshop.data3;
    set workshop.data3;
    birth = input(substr(regnum,1,6), YYMMDD6.);
    today = today();
    age  = int((today-birth)/365.25);
    drop birth today;
run;


  • 우선 substr 함수를 사용해 주민등록번호의 앞자리만 자른 후, 이것을 input 함수를 이용해  YYMMDD6. Informat으로 읽어들여 Numeric으로 변환하여 birth 변수에 저장한다. 
  • today 함수는 오늘 날짜를 numeric으로 돌려준다. 이 숫자 변수는 1960년 1월 1일부터 현재까지의 날짜의 차이를 뜻한다.
  • age는 오늘 날짜에서 출생날짜를 뺀 후 365.25로 나누어준다. 그리고 만 나이이므로 int 함수를 통해 소숫점을 잘라내서 정수로 만들어 준다.
  • 마지막으로 사용한 임시변수 birth, today를 drop해준다.




반응형
반응형

titanic.csv


SAS - (4) PROC FREQ 빈도 분석


PROC FREQ는 빈도분석을 할 때 쓰인다. 


데이터 읽고 솔팅하기


FILENAME REFFILE '/folders/myfolders/titanic.csv';

PROC IMPORT DATAFILE=REFFILE
    DBMS=CSV
    OUT=WORK.titanic;
    GETNAMES=YES;
RUN;

proc sort data = titanic;
    by sex;
run;



PROC FREQ


문법은 아래와 같다.


PROC FREQ DATA = Dataset ;
TABLES Variable_1 ;
BY Variable_2 ;



예제 


proc FREQ data=titanic;
    tables survived; 
    by sex;
run;


결과


FREQ 프로시저

Survived빈도백분율누적
빈도
누적
백분율
08125.808125.80
123374.20314100.00

FREQ 프로시저

Survived빈도백분율누적
빈도
누적
백분율
046881.1146881.11
110918.89577100.00


참고


https://www.tutorialspoint.com/sas/sas_frequency_distributions.htm

반응형
반응형

/*

(3) Standard Deviation 구하기

날짜 : 2017.3.8

*/



데이터 읽기


FILENAME REFFILE '/folders/myfolders/titanic.csv';

PROC IMPORT DATAFILE=REFFILE
    DBMS=CSV
    OUT=WORK.titanic;
    GETNAMES=YES;
RUN;



표준편차 구하기


표준편차도 PROC MEANS 프로시져로 구할 수 있다. 옵션으로 STD를 주면 되며, 산술 평균 구하는 것과 마찬가지로 그루핑 할 수도 있다.

 

PROC MEANS data=work.titanic STD MAXDEC=2;
RUN;



MEANS 프로시저

변수표준편차
PassengerId
Survived
Pclass
Age
Parch
Fare
257.35
0.49
0.84
13.00
0.81
49.69

SORTING


우선 SEX로 그루핑하여 AGE의 Standard Deviation을 구하기에 앞서 SORTING을 먼저한다. 


proc sort data=work.titanic;
    by sex;
run;




PROC SUVEYMEANS


조금 더 Advanced 된 것으로 PROC SURVEYMEANS 프로시져가 있다. 아래는 SEX로 Grouping하여 age의 Standard Deviation을 구하는 예제이다. ods output을 통해 결과를 table로 내보낼 수 있다.


proc surveymeans data=work.titanic STD;
var age;
BY sex; /* 이 때 sex로 sorting이 되어 있어야 한다. */
ods output statistics=rectangle;
run;

proc print data=rectangle;
run;


The SURVEYMEANS Procedure

Data Summary
Number of Observations314
Statistics
VariableStd Error
of Sum
Age228.303304

The SURVEYMEANS Procedure

Distribution of Age

The SURVEYMEANS Procedure

Data Summary
Number of Observations577
Statistics
VariableStd Error
of Sum
Age312.416021

The SURVEYMEANS Procedure

Distribution of Age

OBSSexVarNameStdDev
1femaleAge228.303304
2maleAge312.416021



참고


https://www.tutorialspoint.com/sas/sas_standard_deviation.htm

반응형
반응형

/*

개발환경 : SAS University Edition

날짜 : 2017. 3. 8

*/



(2) PROC SQL로 새로운 테이블 만들기


FILENAME REFFILE '/folders/myfolders/titanic.csv';

PROC IMPORT DATAFILE=REFFILE
    DBMS=CSV
    OUT=WORK.titanic;
    GETNAMES=YES;
RUN;

PROC SQL;
create table titanic_male as
    SELECT *
     FROM 
        work.titanic
            WHERE sex = 'male'
;
RUN;



PROC SQL 입력후 SQL 문으로 새로운 테이블을 생성하는 문장을 넣으면 된다. 위처럼 입력하면 타이타닉 예제에서 sex가 male인 row들만 모아서 새로운 테이블을 만든다. 컬럼을 선택하려면 SELECT column1, column2 처럼 넣으면 된다. 위 스크립트를 실행 후에 work 라이브러리에 가보면 titanic_male이라는 이름의 테이블이 새로 생성되었음을 확인할 수 있다.



출처


https://www.tutorialspoint.com/sas/sas_standard_deviation.htm

반응형
반응형

/*

개발 환경 : SAS University Edition

날짜 : 2017/3/8

*/


titanic.csv



SAS 에서 데이터의 산술 평균은 PROC MEANS 를 통해 구할 수 있다. 예제 데이터셋으로는 titanic 데이터셋을 사용하였다. 



데이터 읽기


/* 소스 파일: titanic.csv */
/* 소스 경로: /folders/myfolders */
/* 코드 생성일: 17. 3. 7. 오후 3:35 */
FILENAME REFFILE '/folders/myfolders/titanic.csv';

PROC IMPORT DATAFILE=REFFILE
    DBMS=CSV
    OUT=WORK.titanic;
    GETNAMES=YES;
RUN;



모든 변수의 평균 구하기


/* 모든 변수의 평균, 합 출력 */
PROC MEANS DATA = WORK.titanic Mean SUM MAXDEC=2;
RUN;



위와 같이 하면 모든 변수의 Mean과 Sum을 구한다. MAXDEC는 Max Decimal의 약자로 소숫점 둘째자리까지 출력하라는 의미이다.



MEANS 프로시저

변수평균합계
PassengerId
Survived
Pclass
Age
Parch
Fare
446.00
0.38
2.31
29.76
0.38
32.20
397386.00
342.00
2057.00
26515.17
340.00
28693.95


특정 변수의 평균 구하기


특정 변수의 평균만 구하고 싶을 때는 VAR 키워드에 지정해준다.


/* 특정 변수의 평균, 합 출력 */
PROC MEANS DATA = WORK.titanic Mean SUM MAXDEC=2;
VAR age;
RUN;


MEANS 프로시저

분석 변수 : Age
평균합계
29.7626515.17

그룹별로 평균 구하기


그룹별로 평균을 구하고 싶을 때는 CLASS 키워드에 지정해준다.

/* 특정 변수의 평균, 합 출력 */

PROC MEANS DATA = WORK.titanic Mean SUM MAXDEC=2; VAR age; CLASS sex; RUN;



MEANS 프로시저

분석 변수 : Age
Sex관측값 수평균합계
female31428.278876.00
male57730.5717639.17

참고



https://www.tutorialspoint.com/sas/sas_arithmetic_mean.htm

반응형

Tools/R

R - (10) 리스트(List)

2017. 3. 4. 01:49
반응형

(10) 리스트 (List)


List 만들기


List와 Vector의 차이점은 Vector는 한 가지 타입의 원소만 담을 수 있지만, List는 어떤 타입이든 담을 수 있다는 것이다.  List는 위와 같이 list() 키워드를 통해 만들 수 있다.


# Create a list containing strings, numbers, vectors and a logical values.
list_data <- list("Red", "Green", c(21,32,11), TRUE, 51.23, 119.1)
print(list_data)



[[1]]
[1] "Red"

[[2]]
[1] "Green"

[[3]]
[1] 21 32 11

[[4]]
[1] TRUE

[[5]]
[1] 51.23

[[6]]
[1] 119.1


출력해보면 위와 같이 첫 번째 원소는 String, 세 번째 원소는 Vector, 네 번째 원소는 진릿값인 것을 알 수 있다.



List에 이름 붙이기 


# Create a list containing a vector, a matrix and a list.
list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2),
   list("green",12.3))

# Give names to the elements in the list.
names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list")

# Show the list.
print(list_data)


$`1st Quarter`
[1] "Jan" "Feb" "Mar"

$A_Matrix
     [,1] [,2] [,3]
[1,]    3    5   -2
[2,]    9    1    8

$`A Inner list`
$`A Inner list`[[1]]
[1] "green"

$`A Inner list`[[2]]
[1] 12.3



위와 같은 문법을 통해 List의 각각의 원소에 이름을 붙일 수 있다. 



리스트 원소 접근


리스트에는 기본적으로 index를 통해 접근할 수 있고, 이름이 붙어져 있으면 이름으로도 접근할 수 있다. 이름으로 접근할 때는 $키워드를 통해 리스트의 이름을 명시해주면 된다.


# Create a list containing a vector, a matrix and a list.
list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2),
   list("green",12.3))

# Give names to the elements in the list.
names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list")

# Access the first element of the list.
print(list_data[1])

# Access the thrid element. As it is also a list, all its elements will be printed.
print(list_data[3])

# Access the list element using the name of the element.
print(list_data$A_Matrix)


$`1st Quarter`
[1] "Jan" "Feb" "Mar"

$`A Inner list`
$`A Inner list`[[1]]
[1] "green"

$`A Inner list`[[2]]
[1] 12.3


     [,1] [,2] [,3]
[1,]    3    5   -2
[2,]    9    1    8



리스트 원소 조작하기 (Manipulating)


리스트 원소 조작은 아래와 같이 <- 키워드를 통해 새로운 값을 넣어주면 된다.


# Create a list containing a vector, a matrix and a list.
list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2),
   list("green",12.3))

# Give names to the elements in the list.
names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list")

# Add element at the end of the list.
list_data[4] <- "New element"
print(list_data[4])

# Remove the last element.
list_data[4] <- NULL

# Print the 4th Element.
print(list_data[4])

# Update the 3rd Element.
list_data[3] <- "updated element"
print(list_data[3])

[[1]]
[1] "New element"

$<NA>
NULL

$`A Inner list`
[1] "updated element"


리스트 합치기


아래와 같이 c() 키워드를 통해 리스트를 합칠 수 있다. 


# Create two lists.
list1 <- list(1,2,3)
list2 <- list("Sun","Mon","Tue")

# Merge the two lists.
merged.list <- c(list1,list2)

# Print the merged list.
print(merged.list)


[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] "Sun"

[[5]]
[1] "Mon"

[[6]]
[1] "Tue"


리스트를 벡터로 변환하기


List 상태에서는 벡터 상태에서 보다 조작의 자유도가 떨어진다. 예를 들어 산술 연산을 한다거나 할 수 없다. 다양한 조작을 위해 리스트를 벡터로 변환할 때는 아래와 같이 unlist() 키워드를 이용하면 된다. 


# Create lists.
list1 <- list(1:5)
print(list1)

list2 <-list(10:14)
print(list2)

# Convert the lists to vectors.
v1 <- unlist(list1)
v2 <- unlist(list2)

print(v1)
print(v2)

# Now add the vectors
result <- v1+v2
print(result)


[[1]]
[1] 1 2 3 4 5

[[1]]
[1] 10 11 12 13 14

[1] 1 2 3 4 5
[1] 10 11 12 13 14
[1] 11 13 15 17 19



아래 튜토리얼을 참고한 포스팅입니다.


https://www.tutorialspoint.com/r/r_lists.htm

반응형
반응형


R 통계분석 Mean, Median, Mode


R을 통한 통계분석은 많은 in-built 함수들을 통해 이루어진다. 이러한 함수들은 대부분 R base package에 속해있고, vector들을 다른 argument들과 함께 input으로 받아 결과를 출력해준다. 이번 포스팅에 다룰 내용은 mean, median, mode 함수이다. 



1. Mean 


문법 


mean(x, trim = 0, na.rm = FALSE, ...)


  • x : input vector
  • trim : 정렬된 vector에서 양 극단에서의 일정 부분을 뺄 때 사용함
  • na.rm : missing value를 제거하고 계산할 때 사용

예제

# Create a vector. 
x <- c(12,7,3,4.2,18,2,54,-21,8,-5)

# Find Mean.
result.mean <- mean(x)
print(result.mean)


[1] 8.22



Trim Option 사용하기


# Create a vector.
x <- c(12,7,3,4.2,18,2,54,-21,8,-5)

# Find Mean.
result.mean <-  mean(x,trim = 0.3)
print(result.mean)


Trim을 사용하면 양 극단에서 일정부분을 빼고 계산한다. 0.3일 경우 양 끝에서 전체 데이터의 0.3 만큼을 제외한다. 이 경우에 전체데이터가 10개이므로 양 끝에서 3개씩을 뺀다. 즉 정렬된 벡터 (−21, −5, 2, 3, 4.2, 7, 8, 12, 18, 54) 에서 (−21,−5,2) (12,18,54) 을 뺀 평균을 계산한다. 



NA 옵션 적용하기


# Create a vector. 
x <- c(12,7,3,4.2,18,2,54,-21,8,-5,NA)

# Find mean.
result.mean <-  mean(x)
print(result.mean)

# Find mean dropping NA values.
result.mean <-  mean(x,na.rm = TRUE)
print(result.mean)


[1] NA
[1] 8.22


원래는 오류가 날 것을 na.rm=TRUE 를 통해 NA 값을 제거하고 평균을 구할 수 있다.



2. Median


Median(중위수)는 전체 데이터에서 중앙에 있는 값을 뜻한다. Median() 함수는 이 값을 구하기 위해 사용된다.


문법 


median(x, na.rm = FALSE)



# Create the vector.
x <- c(12,7,3,4.2,18,2,54,-21,8,-5)

# Find the median.
median.result <- median(x)
print(median.result)



3. Mode 


Mode(최빈값)은 데이터에서 가장 많이 등장한 값이다. 안타깝게도 R에는 Mode를 구하는 in-built function이 없다. 직접 정의한 getmode() 함수를 통해 Mode를 구해보자.


# Create the function.
getmode <- function(v) {
   uniqv <- unique(v)
   uniqv[which.max(tabulate(match(v, uniqv)))]
}

# Create the vector with numbers.
v <- c(2,1,2,3,1,2,3,4,1,5,5,3,2,3)

# Calculate the mode using the user function.
result <- getmode(v)
print(result)

# Create the vector with characters.
charv <- c("o","it","the","it","it")

# Calculate the mode using the user function.
result <- getmode(charv)
print(result)


[1] 2
[1] "it"



이렇게 정의된 getmode 함수는 위처럼 문자열에도 적용할 수 있다.



아래 튜토리얼을 참고한 포스팅입니다.

https://www.tutorialspoint.com/r/r_mean_median_mode.htm

반응형

'Tools > R' 카테고리의 다른 글

R - 단순회귀분석  (0) 2017.05.21
R - (10) 리스트(List)  (0) 2017.03.04
R - (9) 벡터  (0) 2017.02.23
R - (8) 문자열 (Strings)  (0) 2017.02.23
R을 통한 2017년 대선 주자들 페이스북 분석  (5) 2017.02.21

Tools/R

R - (9) 벡터

2017. 2. 23. 16:37
반응형

(9) 벡터 (Vectors)


벡터는 가장 기본적인 R의 Data Object이다. 우선 기본적으로 6개의 atomic vector들을 알아야할 필요가 있다.  이 6개의 atomic vectors는 이전 포스팅 에도 소개하였지만, logical, integer, double, complex, character, raw이다. 아래의 예를 통해 복습하자.


# Atomic vector of type character.
print("abc");

# Atomic vector of type double.
print(12.5)

# Atomic vector of type integer.
print(63L)

# Atomic vector of type logical.
print(TRUE)

# Atomic vector of type complex.
print(2+3i)

# Atomic vector of type raw.
print(charToRaw('hello'))


1. 벡터의 원소에 접근하기


벡터의 원소에는 인덱스를 통해 접근할 수 있다. [](brackets) 이 인덱싱을 위해 필요하다. 인덱싱은 다른 프로그래밍 언어와는 다르게 1부터 시작한다.  또한 - 인덱싱은 해당 엘리먼트를 결과값에서 제외한다는 뜻이다. TRUE, FALSE, 0, 1도 인덱싱을 위해 사용될 수 있다. 아래의 예를 보자.


# Accessing vector elements using position.
t <- c("Sun","Mon","Tue","Wed","Thurs","Fri","Sat")
u <- t[c(2,3,6)]
print(u)

# Accessing vector elements using logical indexing.
v <- t[c(TRUE,FALSE,FALSE,FALSE,FALSE,TRUE,FALSE)]
print(v)

# Accessing vector elements using negative indexing.
x <- t[c(-2,-5)]
print(x)

# Accessing vector elements using 0/1 indexing.
y <- t[c(0,0,0,0,0,0,1)]
print(y)


[1] "Mon" "Tue" "Fri"
[1] "Sun" "Fri"
[1] "Sun" "Tue" "Wed" "Fri" "Sat"
[1] "Sun"



2. 벡터 조작하기


(1) 벡터 연산


길이가 같은 벡터들은 더하고, 빼고, 곱하고, 나누고 할 수 있다.


# Create two vectors.
v1 <- c(3,8,4,5,0,11)
v2 <- c(4,11,0,8,1,2)

# Vector addition.
add.result <- v1+v2
print(add.result)

# Vector substraction.
sub.result <- v1-v2
print(sub.result)

# Vector multiplication.
multi.result <- v1*v2
print(multi.result)

# Vector division.
divi.result <- v1/v2
print(divi.result)



[1]  7 19  4 13  1 13
[1] -1 -3  4 -3 -1  9
[1] 12 88  0 40  0 22
[1] 0.7500000 0.7272727       Inf 0.6250000 0.0000000 5.5000000



(2) 벡터 엘리먼트 재사용


만약 두 개의 벡터를 연산하려는데 길이가 다르면, 짧은 쪽의 벡터의 원소가 재사용된다.


v1 <- c(3,8,4,5,0,11)
v2 <- c(4,11)
# V2 becomes c(4,11,4,11,4,11)

add.result <- v1+v2
print(add.result)

sub.result <- v1-v2
print(sub.result)


[1]  7 19  8 16  4 22
[1] -1 -3  0 -6 -4  0

위의 결과를 보면 v2가 (4,11) 에서 (4,11,4,11,4,11)로 바뀌었음을 알 수 있다. 연산을 하기 위해 (4,11)이 재사용된 것이다.



(3) 벡터 엘리먼트 정렬


벡터들의 엘리먼트는 sort() 함수를 통해 정렬될 수 있다.


v <- c(3,8,4,5,0,11, -9, 304)

# Sort the elements of the vector.
sort.result <- sort(v)
print(sort.result)

# Sort the elements in the reverse order.
revsort.result <- sort(v, decreasing = TRUE)
print(revsort.result)

# Sorting character vectors.
v <- c("Red","Blue","yellow","violet")
sort.result <- sort(v)
print(sort.result)

# Sorting character vectors in reverse order.
revsort.result <- sort(v, decreasing = TRUE)
print(revsort.result)


[1]  -9   0   3   4   5   8  11 304
[1] 304  11   8   5   4   3   0  -9
[1] "Blue"   "Red"    "violet" "yellow"
[1] "yellow" "violet" "Red"    "Blue"  




반응형
반응형
(8) 문자열 (Strings)


R에서 쌍따옴표나 작은 따옴표로 둘러쌓인것은 문자열로 취급된다. 


문자열을 만들 때 주의할점

  • 문자열은 만들 때, 쌍따옴표 혹은 작은따옴표만을 사용하여야한다. 두개를 혼합하여 사용하면 안된다.
  • 쌍따옴표는 작은따옴표 사이에 들어갈 수 잇다.
  • 작은 따옴표는 쌍따옴표 사이에 들어갈 수 있다.
  • 쌍따옴표는 쌍따옴표 사이에 들어갈 수 없다.
  • 작은따옴표는 작은따옴표 사이에 들어갈 수 없다.

적절한 문자열들의 예

a <- 'Start and end with single quote'
print(a)

b <- "Start and end with double quotes"
print(b)

c <- "single quote ' in between double quotes"
print(c)

d <- 'Double quotes " in between single quote'
print(d)


[1] "Start and end with single quote"
[1] "Start and end with double quotes"
[1] "single quote ' in between double quotes"
[1] "Double quotes \" in between single quote"


부적절한 문자열들의 예

e <- 'Mixed quotes" 
print(e)

f <- 'Single quote ' inside single quote'
print(f)

g <- "Double quotes " inside double quotes"
print(g)


문자열 조작(manipulation)

1. paste()

설명 : 두 개의 문자열을 연결(Concatenating)할 때 사용한다.
문법 : paste(..., sep = " ", collapse = NULL)

예 : 

a <- "Hello"
b <- 'How'
c <- "are you? "

print(paste(a,b,c))

print(paste(a,b,c, sep = "-"))

print(paste(a,b,c, sep = "", collapse = ""))

[1] "Hello How are you? "
[1] "Hello-How-are you? "
[1] "HelloHoware you? "

2. format()

설명 : 문자나 숫자를 원하는 포맷으로 변경한다.

문법 : format(x, digits, nsmall, scientific, width, justify = c("left", "right", "centre", "none"))

  • x : 벡터 input
  • digits : 출력할 총 자릿수
  • nsmall : 소숫점 우측의 최소 자릿수
  • scientific : TRUE이면 scientific notation을 함
  • width : 최소 width (왼쪽에 blank를 넣어 width를 맞춘다.)
  • justify : 정렬할 위치 (좌측정렬, 가운데 정렬, 우측정렬)

# Total number of digits displayed. Last digit rounded off.
result <- format(23.123456789, digits = 9)
print(result)

# Display numbers in scientific notation.
result <- format(c(6, 13.14521), scientific = TRUE)
print(result)

# The minimum number of digits to the right of the decimal point.
result <- format(23.47, nsmall = 5)
print(result)

# Format treats everything as a string.
result <- format(6)
print(result)

# Numbers are padded with blank in the beginning for width.
result <- format(13.7, width = 6)
print(result)

# Left justify strings.
result <- format("Hello", width = 8, justify = "l")
print(result)

# Justfy string with center.
result <- format("Hello", width = 8, justify = "c")
print(result)

[1] "23.1234568"
[1] "6.000000e+00" "1.314521e+01"
[1] "23.47000"
[1] "6"
[1] "  13.7"
[1] "Hello   "
[1] " Hello  "

3. nchar()

설명 : 문자의 갯수를 세준다. (공백도 포함한다.)
예 :

result <- nchar("Count the number of characters")
print(result)

[1] 30


4. toupper(), tolower()

설명 : 문자열을 대문자로 바꾼다 / 문자열을 모두 소문자로 바꾼다.

생략 

5. substring()

설명 : 문자열의 일부를 추출한다.
문법 : substring(x,first,last)
예 : 

# Extract characters from 5th to 7th position.
result <- substring("Extract", 5, 7)
print(result)

[1] "act"

아래 튜토리얼을 참고한 포스팅입니다. 

https://www.tutorialspoint.com/r/r_operators.htm 



반응형

'Tools > R' 카테고리의 다른 글

R 통계 분석 - 평균, 중앙값, 최빈값 (Mean, Median, Mode)  (0) 2017.02.23
R - (9) 벡터  (0) 2017.02.23
R을 통한 2017년 대선 주자들 페이스북 분석  (5) 2017.02.21
R - (7) 함수  (0) 2017.02.19
R - (6) 반복문  (0) 2017.02.17
반응형

R 연습도 할겸, 재미로 대선 주자들(문재인, 이재명, 안희정, 황교안, 안철수, 유승민) 총 6명의 페이스북 페이지를 분석해 보았습니다. 분석에는 R을 사용하였고 Facebook API를 구현한 Rfacebook 패키지를 이용하였습니다. 


2016년 11월 1일 ~ 2016년 2월 19일 분석 기간으로 정하였고, 총 3가지에 관하여 분석해보았습니다. 


  • 총 포스팅 횟수
  • 포스팅당 평균 좋아요 수
  • 날짜별 좋아요수 변화 그래프 


총 포스팅 횟수




총 포스팅 횟수는 이재명-안철수-문재인 순으로 나타났습니다. 이재명과 안철수가 해당 기간 (2016년 11월 1일 ~ 2017년 2월 19일) 동안 300개가 넘는 포스팅으로 나란히 1, 2위를 차지하였고, 페이스북 포스팅에 적극적인 모습을 보였습니다. 반면 6등인 황교안은 83 포스팅으로 가장 적은 포스팅을 하였습니다.



포스팅당 평균 좋아요 수





포스팅당 평균 좋아요수는 위와 같이 나타났습니다. 문재인이 포스팅당 6146로 다른 후보들과 비교하여 압도적인 좋아요수를 기록하였고 2위인 안희정과 비교하여 거의 2배의 평균 좋아요 수를 보였습니다. 이를 실제 대선 주자 지지도 조사와 비교하여볼까요?






리얼미터에서 조사한 대선후보 지지율은 위와 같습니다. 문재인-안희정-황교안-안철수-이재명-유승민 순입니다. 페이스북 페이지 평균 좋아요수는 문재인-안희정-황교안-이재명-안철수-유승민 순으로 단순 순위만 봤을 때 안철수, 이재명의 차이만 빼고는 같다는 것을 알 수 있습니다. 이를 해석해보면 이재명은 페이스북에서 비교적 인기가 많다고도 볼 수 있을것 같습니다. 주로 20, 30대들이 페이스북을 많이하니 20, 30대들이 좋아하는 이재명이 페이스북에서 강세를 보이는 것으로 보입니다.



날짜별 좋아요수 변화 그래프





다음은 날짜별로 좋아요 수가 어떻게 변하는지 그래프를 그려보았는데요. 자세히 보시면 문재인 후보의 좋아요수가 평균적으로 점점 감소해가는 것을 볼 수 있습니다. 또한 자세히 보시면 안희정 후보들의 포스팅에서 최근들어 좋아요를 많이 받은 포스팅이 점점 많아지는 것이 보입니다. 다른 후보들에서는 생각외로 뚜렷한 패턴을 발견할 수 없어보이네요.



이러한 분석을 통해 대선 결과를 예측하거나 할 수는 없을 것 같습니다. 단순한 통계 분석에 그치기 때문입니다. 그냥 재미로 봐주셨으면 좋겠습니다. 하지만 최근 많이 사용하는 텍스트 마이닝, 감정 분석등의 머신러닝 알고리즘을 통해 네티즌들의 반응, 포스팅 내용 등을 분석하면 조금 더 깊고 의미있는 통찰을 할 수 있을 것입니다.



제가 사용한 R 코드는 아래에 첨부합니다. 


facebook.R


# https://cran.r-project.org/web/packages/Rfacebook/Rfacebook.pdf
library(Rfacebook)
library(ggplot2)
library(scales)
# get auth token
fb_oauth = fbOAuth(app_id = "310016876042099", app_secret = "6772bfc30e27720eac8d67122157aa47", extended_permissions = FALSE)

# 해당 페이지의 시작날짜와 종료날짜 사이의 모든 포스트 가져옴
getPosts <- function(page_name, start_date, end_date) {
  # 날짜 sequence
  scrape_days <- seq(from=as.Date(start_date), to=as.Date(end_date), by='days')
  posts = c()
  for(scrape_day in scrape_days){
    daypost = c()
    tryCatch({
      daypost = getPage(page=page_name, token=fb_oauth,
                        since=as.Date(scrape_day, origin='1970-01-01'),
                        until=as.Date(scrape_day, origin='1970-01-01')+1)},
      error = function(e){})
    posts = rbind(posts, daypost)
  }
  return(posts)
}

drawLikeGraph <- function(data){
  ggplot(data, aes(x=created_time, y=likes_count)) + geom_line() + 
    theme_bw() + scale_x_date(labels = date_format("%m-%Y")) +
    labs(x = "날짜(MM-yyyy)", y = "좋아요수(n)") + 
    ggtitle(paste(start_date, end_date, sep="~"))
}

drawPostNumGraph <- function(data){
  ggplot(data=data, aes(x=name, y=num, fill=name)) +
    geom_bar(stat="identity", width=0.8) +
    labs(x='대선주자', y='포스트수') +
    geom_text(aes(label=num), vjust=1.6, color="white", size=3.5) +
    theme_minimal() +
    ggtitle(paste(start_date, end_date, sep="~"))
}

drawAverageLikeGraph <- function(data){
  ggplot(data=data, aes(x=name, y=average_like, fill=name)) +
    geom_bar(stat="identity", width=0.8) +
    labs(x='대선주자', y='평균 좋아요수') +
    geom_text(aes(label=round(average_like, 0)), vjust=1.6, color="white", size=3.5) +
    theme_minimal() +
    ggtitle(paste(start_date, end_date, sep="~"))
}

getSummaryDataFrame <- function(posts, name){
  average_like = sum(posts$likes_count)/nrow(posts)
  summary <- data.frame(name=name, num=nrow(posts),
                        average_like=average_like)
  return(summary)
}

moon_page = "moonbyun1" # 문재인 페이지 
lee_page = "jaemyunglee1" # 이재명 페이지
hwang_page = "PM0415HwangKyoahn" # 황교안 페이지
yoo_page = "yooseongmin21" # 유승민 페이지
ahn_hwee_page = "steelroot" # 안희정 페이지
ahn_chul_page = "ahncs111" # 안철수 페이

start_date <- '2016/11/01' # 시작 날짜
end_date <- '2017/02/19' # 종료 날짜

moon_posts <- getPosts(moon_page, start_date, end_date)
lee_posts <- getPosts(lee_page, start_date, end_date)
hwang_posts <- getPosts(hwang_page, start_date, end_date)
yoo_posts <- getPosts(yoo_page, start_date, end_date)
ahn_hwee_posts <- getPosts(ahn_hwee_page, start_date, end_date)
ahn_chul_posts <- getPosts(ahn_chul_page, start_date, end_date)

print(nrow(hwang_posts))

# preprocess
moon_posts$created_time <- as.Date(moon_posts$created_time) # string to date
lee_posts$created_time <- as.Date(lee_posts$created_time)
hwang_posts$created_time <- as.Date(hwang_posts$created_time)
yoo_posts$created_time <- as.Date(yoo_posts$created_time)
ahn_hwee_posts$created_time <- as.Date(ahn_hwee_posts$created_time)
ahn_chul_posts$created_time <- as.Date(ahn_chul_posts$created_time)

# summary 데이터 프레임 만듦
moon_summary <- getSummaryDataFrame(moon_posts, '문재인')
lee_summary <- getSummaryDataFrame(lee_posts, '이재명')
hwang_summary <- getSummaryDataFrame(hwang_posts, '황교안')
yoo_summary <- getSummaryDataFrame(yoo_posts, '유승민')
ahn_hwee_summary <- getSummaryDataFrame(ahn_hwee_posts, '안희정')
ahn_chul_summary <- getSummaryDataFrame(ahn_chul_posts, '안철수')

summary <- data.frame() # 빈 데이터 프레임을 만듦
summary <- rbind(summary, moon_summary) # 행추가
summary <- rbind(summary, lee_summary)
summary <- rbind(summary, hwang_summary)
summary <- rbind(summary, yoo_summary)
summary <- rbind(summary, ahn_hwee_summary)
summary <- rbind(summary, ahn_chul_summary)

drawPostNumGraph(summary)
drawAverageLikeGraph(summary)

# reactions <- getReactions(post=posts$id, fb_oauth, verbose=TRUE)
drawLikeGraph(moon_posts)
drawLikeGraph(lee_posts)
drawLikeGraph(hwang_posts)
drawLikeGraph(yoo_posts)
drawLikeGraph(ahn_hwee_posts)
drawLikeGraph(ahn_chul_posts)

all_posts <- data.frame()
all_posts <- rbind(all_posts, moon_posts)
all_posts <- rbind(all_posts, lee_posts)
all_posts <- rbind(all_posts, hwang_posts)
all_posts <- rbind(all_posts, yoo_posts)
all_posts <- rbind(all_posts, ahn_hwee_posts)
all_posts <- rbind(all_posts, ahn_chul_posts)

ggplot(all_posts, aes(x=created_time, y=likes_count, group=from_name, colour=from_name)) + geom_line(size=0.5) + 
  geom_smooth() +
  theme_minimal() + scale_x_date(labels = date_format("%m-%Y")) +
  labs(x = "날짜(MM-yyyy)", y = "좋아요수(n)") + 
  ggtitle(paste(start_date, end_date, sep="~"))


반응형

'Tools > R' 카테고리의 다른 글

R - (9) 벡터  (0) 2017.02.23
R - (8) 문자열 (Strings)  (0) 2017.02.23
R - (7) 함수  (0) 2017.02.19
R - (6) 반복문  (0) 2017.02.17
R - (5) If, else if, switch  (0) 2017.02.15
반응형