2020/11/13回家作業

變數處理

#第一步 讀入SPSS檔案

library(foreign)
library(sjlabelled)
library(sjPlot)
## #refugeeswelcome
id15 <- read.spss("Total.sav",
                  reencode="big5",
                  use.value.labels= F, 
                  to.data.frame = T) 
## re-encoding from big5

第二步 使用sjmisc::set_na()指令清理無效值

library(sjmisc)
## 
## Attaching package: 'sjmisc'
## The following objects are masked from 'package:sjlabelled':
## 
##     to_character, to_factor, to_label, to_numeric
id15 <- set_na(id15, na=c(92:99, "NA")) 

第四步:使用sjmisc::rec()指令為變數編碼

library(sjmisc)

給定每個受訪者一個id

names(id15)
##  [1] "V1"     "V2"     "V3"     "V4"     "V5"     "VA4"    "VA5"    "V6"    
##  [9] "V7"     "V8"     "V9"     "V10"    "V11"    "V12"    "V13"    "V14"   
## [17] "V15"    "V16"    "V17"    "V18"    "V19"    "V20"    "V21"    "V22"   
## [25] "V23"    "V24"    "V25"    "V26"    "V27"    "V28"    "V29"    "V30"   
## [33] "V31"    "V32"    "VB4"    "VB5"    "V33"    "V34"    "V35"    "V36"   
## [41] "V37_1"  "V37_2"  "S1"     "REC_NO" "KA5_0"  "KB5_0"  "K34_0"  "K37_0" 
## [49] "K37_1"  "Q33"    "Q34"    "AGE1"   "AGE2"   "EDU"    "PID1"   "PID2"  
## [57] "Q35"    "WEIGHT"
id15$id <- 1:nrow(id15)

1、性別:【訪員判斷後勾選】

(01)男 (02)女

library(sjmisc)
id15$V1r <- rec(id15$V1, rec = "1=1; 2=0", as.num = F)

4、在我們的社會裡,大部份的人對政治都有自己的看法。請問,一般來講,您覺得在目前的政黨當中,哪一個黨的主張,比較接近您自己的看法

(01)國民黨 (02)親民黨 (03)傾泛藍 (04)民進黨 (05)台聯 (06)傾泛綠 (07)中立/不一定/看人不看黨 (98)不知道/未回答

27、請問,以台灣和大陸的關係來講,您比較贊成統一、獨立,或是維持現狀?

【若答維持現狀,則追問選項(02)~(05)】

(01)獨立 (02)維持現狀,以後獨立 (03)維持現狀,看情形再說 (04)永遠維持現狀 (05)維持現狀,以後統一 (06)統一 (98)不知道/無意見/未回答

將年齡重新編碼為六個政治世代

id15$generation <- NA
id15$generation[id15$Q34>=(2015-1931)] <- 1
id15$generation[id15$Q34<=(2015-1932) & id15$Q34>=(2015-1953)] <- 2
id15$generation[id15$Q34<=(2015-1954) & id15$Q34>=(2015-1968)] <- 3
id15$generation[id15$Q34<=(2015-1969) & id15$Q34>=(2015-1978)] <- 4
id15$generation[id15$Q34<=(2015-1979) & id15$Q34>=(2015-1988)] <- 5
id15$generation[id15$Q34<=(2015-1989)] <- 6  #less than 26

id15$gen.1 <- ifelse(id15$generation==1,1,0)
id15$gen.2 <- ifelse(id15$generation==2,1,0)
id15$gen.3 <- ifelse(id15$generation==3,1,0)
id15$gen.4 <- ifelse(id15$generation==4,1,0)
id15$gen.5 <- ifelse(id15$generation==5,1,0)
id15$gen.6 <- ifelse(id15$generation==6,1,0)

第五步(非必要步驟):判斷並移除不必要的欄位

移除不需要變數(例如不可公開或傳遞的生日或手機欄位)的三個方法:

方法一:欄位連同標籤一個一個消除

id15$V37_1 <- NULL
id15$V37_2 <- NULL
id15$K37_0 <- NULL
id15$K37_1 <- NULL

嘗試變數相關性檢定

sjt.xtab(id15$V4,id15$V27)
V4 V27 Total
1 2 3 4 5 6
1 16 10 62 27 29 18 162
2 1 1 6 0 0 1 9
3 3 2 12 6 4 3 30
4 110 41 69 34 14 4 272
5 3 1 0 1 0 0 5
6 17 4 1 4 1 0 27
7 78 36 187 98 20 17 436
Total 228 95 337 170 68 43 941
χ2=183.169 · df=30 · Cramer’s V=0.197 · Fisher’s p=0.000

第六步:將包含標籤資訊的資料檔另存為rda檔或sav檔

save(id15, file = "id15.rda") #存為rda
sjlabelled::write_spss(id15, "id15.sav") #存為sav 
## Tidying value labels. Please wait...
## Writing spss file to 'id15.sav'. Please wait...