2008年3月23日 星期日

SPSS-如何整理資料檔案

1. 重新編碼







SPSS功能列 ⇒資料⇒重新編碼







重新編碼的功能在於將變數既有的數值重新設定。當使用者遇到變數的數值必需進行轉換時,可使用此功能。重新編碼可以將資料輸出為成不同變數(不會將原來的資料取代置換),也可輸出成相同變數(會將原來的資料置換),是個人需要而定。以Employee data.sav為例,由於原始資料性別變數屬性為文字,男:gender=m、女:gender=f。若想將他轉變為數值資料的新變數,男:sex= 1、女:sex=0,則可以下列步驟進行轉換:







Step 1. 將gender輸入數值變數,新變數名稱中鍵入sex,並按變更。











Step 2. 分別輸入舊值=m及新值=1,並按新增;同樣的方法,分別輸入舊值=f及新值=0。











執行之後,你會發現資料視窗會多出一新變數sex。




2. 分割檔案







SPSS功能列 ⇒資料⇒分割檔案







分割檔案可以根據某個類別變數,將資料劃分成不同的組別並進行分析。所以,當我們想依據某一類別變數分組作特定一項分析,此時我們就可以利用SPSS裡『分割檔案』的功能。以Employee data.sav為例,若想針對不同的性別分別利用迴歸分析探討教育程度對起薪的影響,則利用分割檔案功能,依照性別(男:gender=1,女:gender=0)將資料跟割成兩個群。











接下來進行迴歸分析,你會發現SPSS將依照不同的性別分別進行迴歸分析並輸出報表。分割檔案的選項中有『比較組別』及『依組別組織輸出』兩種。







必須注意的是,在SPSS中最多可以指定八個分組變數;如果定義了分割,則它會在以後的所有統計分析中起作用,直到你重新定義分割方式為止。




3. 選擇觀察值







SPSS功能列 ⇒資料⇒選擇觀察值







當我們只想針對類別變數中的某一類別作特定一項分析,此時我們就可以利用SPSS裡『選擇觀察值』所提供的方法,來選擇觀察值子集。以Employee data.sav為例,若只想針對男性作迴歸分析探討教育程度對起薪的影響,利用『選擇觀察值』功能來設定資料選取準則。







Step 1.











Step 2.



執行之後,你會發現資料視窗的最右邊列號有些有斜線,有些則沒有。有斜線的表示未被選取的資料。











當然,有時候會需要更複雜的選取準則,SPSS也提供條件運算式。大部分的條件運算式都可以使用計算機面板上得六個相關算子及邏輯變數,例如:>、<、<=、>=、=、∼=、&、|以及∼等。茲舉例如下:







  • And:『\&』,例如:輸入『jobcat=3 & gender=1』表示選取性別為男性且職稱為職員的資料










  • Or:『$\mid$』,例如:輸入『gender=1 | gender=3』表示選職稱為職員或管理主管的資料










  • Not:『$\sim$』,例如:輸入『~ jobcat=2』表示選職稱不是保全人員的資料








4. 類別化變數







SPSS功能列 ⇒轉換⇒類別化變數







『類別化變數』會將連續數值資料轉換為非連續類別變數並建立新變數。資料會依據百分位數組別分類,每個組別包含數目近似的觀察值。例如,將資料分為4的組別會指定1給低於25百分位數、指定2給介於25和50百分位數、指定3給的介於50和75百分位數,並指定4給超過75百分位數的觀察值。以Employee data.sav為例,若想了解教育程度與起薪是否有關,可將上述兩變數以類別化資料各分為4組,在以卡分檢定分析。












5. 計算







SPSS功能列 ⇒轉換⇒計算







『計算』可以根據其他變數來作數值轉換或計算成某個變數的數值,大部分的運算式都可以使用計算機面板或使用內建函數完成。以Employee data.sav為例,若想將薪資轉換為以千元為單位,首先在目標變數中輸入新變數名稱Nsalary,接下來在數值運算式中輸入salary/1000即可產生nsalary這個新變數。












Chi-Square Plot by SPSS



The Chi-Square Plot plots the ordered robust mahalanobis distances of the data against the quantiles of the Chi-squared distribution. If the data is normal distributed these values should approximately correspond to each other, so outliers can be detected visually. By user interaction this procedure is repeated, each time leaving out the observation with the greatest distance (the number of the observation is printed on the console). This method can be seen as an iterativ deletion of outliers until a straight line appears. I write this syntax to plot it. If you have any problem, please let me know.



SET MXLOOP =99999.
MATRIX.
GET DATA/VARIABLES=X1 to X4/MISSING=OMIT.
COMPUTE NR=NROW(DATA).
COMPUTE NC=NCOL(DATA).
COMPUTE MEAN=T(CSUM(DATA)/NR).
PRINT MEAN.
COMPUTE SIGMA=(SSCP(DATA)-NR*MEAN*T(MEAN))/(NR-1).
PRINT SIGMA.
COMPUTE MD=MAKE(NR,2,-999).
COMPUTE MDTEMP=MAKE(NR,1,-999).
LOOP I=1 TO NR.
- COMPUTE MD(I,1)=DATA(I,:)*INV(SIGMA)*T(DATA(I,:)).
END LOOP.
COMPUTE MD(:,2)=(RNKORDER(MD(:,1))-0.5)/NR.
SAVE MD /OUTFILE=*.
END MATRIX.
RENAME VARIABLES COL1= MD COL2= CHISQUARE.
GRAPH
/SCATTERPLOT(BIVAR)=MD WITH CHISQUARE /MISSING=LISTWISE
/TITLE= 'The chi-square plot of the ordered distances
.'.

2008年3月18日 星期二

統計分析講義





這是我今年上EMBA統計分析所撰寫的講義,幫這本講義寫個序



我打研究室走過

那獨坐電腦前的容顏如苦瓜的糾結

靈感不來,長壽的煙霧不散

研究室如小小的寂寞的城

恰如商管的電梯向晚



鍵盤不響,彈菸的手指不歇

看動作片要把小小的窗屝緊掩

我達達的馬蹄是美麗的錯誤

我不是主人,是個過客



講義的章節分配如下:

Ch 1. 資料的統計量數

Ch 2. 區間估計與假設檢定

Ch 3. 卡方檢定

Ch 4. 變異數分析

Ch 5. 簡單線性迴歸分析

Ch 6. 多元迴歸分析

Ch 7. 主成份分析

Ch 8. 因素分析

Ch 9. 典型相關分析

Ch 10. 區別分析

Appendix A. 整理資料檔案



我已經將數理推導的部份作適當的精簡,在每個章節後面,也以統計軟體SPSS 10.0來當作統計分析的工具。最終的目的,是希望能夠讓同學對統計不會有太大的恐懼感。



當然,由於時間充促,遺漏或錯誤在所難免,希望各位先進不吝指教。





2008年3月17日 星期一

SPSS Matrix Language

The following matrix language statements can be used in a matrix program:

BREAK
DO IF...END IF
LOOP...END LOOP
MSAVE
SAVE
CALL
GET
PRINT
WRITE
COMPUTE
READ
DISPLAY
END IF
MGET
RELEASE


The following functions can be used in matrix language statements:

ABS:Absolute values of matrix elements
ALL:Test if all elements are positive
ANY:Test if any element is positive
ARSIN:Arcsines of matrix elements
ARTAN:Arctangents of matrix elements
BLOCK:Create block diagonal matrix
CDFNORM:Cumulative normal distribution function
CHICDF:Cumulative chi-squared distribution function
CHOL:Cholesky decomposition
CMAX:Column maxima
CMIN:Column minima
CSSQ:Column sums of squares
CSUM:Column sums
DESIGN:Create design matrix
DET:Determinant
DIAG:Diagonal of matrix
EOF:Check end of file
EVAL:Eigenvalues of symmetric matrix
EXP:Exponentials of matrix elements
FCDF:Cumulative F distribution function
GINV:Generalized inverse
GRADE:Rank elements in matrix, using sequential integers for ties
GSCH:Gram-Schmidt orthonormal basis
IDENT:Create identity matrix
INV:Inverse
LG10:Logarithms to base 10 of matrix elements
LN:Logarithms to base e of matrix elements
MAGIC:Create magic square
MAKE:Create a matrix with all elements equal
MDIAG:Create a matrix with the given diagonal
MMAX:Maximum element in matrix
MMIN:Minimum element in matrix
MOD:Remainders after division
MSSQ:Matrix sum of squares
MSUM:Matrix sum
NCOL:Number of columns
NROW:Number of rows
RANK:Matrix rank
RESHAPE:Change shape of matrix
RMAX:Row maxima
RMIN:Row minima
RND:Round off matrix elements to nearest integer
RNKORDER:Rank elements in matrix, averaging ties
RSSQ:Row sums of squares
RSUM:Row sums
SIN:Sines of matrix elements
SOLVE:Solve systems of linear equations
SQRT:Square roots of matrix elements
SSCP:Sums of squares and cross-products
SVAL:Singular values
SWEEP:Perform sweep transformation
T:Synonym for TRANSPOS
TCDF:Cumulative normal t distribution function
TRACE:Calculate trace (sum of diagonal elements)
TRANSPOS:Transposition of matrix
TRUNC:Truncation of matrix elements to integer
UNIFORM:Create matrix of uniform random numbers

2008年3月16日 星期日

用VBA抓Yahoo拍賣買家的帳號

用VBA抓Yahoo拍賣買家的帳號,雖然我不知道做這個有什麼用。但是在PTT上倒是很多人有這個需要。無聊寫的VBA,程式碼如下:

Sub Yahoo()
Dim Fn As Object
Set Fn = Application.WorksheetFunction
yahooid = "nardi7225"
endpage = 10
Index1 = 0
For i = 1 To endpage
Range("A" & i + Index1).Select
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;http://tw.user.bid.yahoo.com/tw/show/rating?userID=" & yahooid & "&pageNo=" & i _
& "&filter=0" _
, Destination:=Range("A" & i + Index1))
.FieldNames = False
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = False
.RefreshPeriod = 0
.WebSelectionType = xlSpecifiedTables
.WebFormatting = xlWebFormattingNone
.WebTables = "10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,51"
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With
Index1 = Index1 + 39
Next
Range("A:B").Select
Selection.Sort Key1:=Range("A1"), Order1:=xlAscending, Key2:=Range("B1") _
, Order2:=xlAscending, Header:=xlGuess, OrderCustom:=1, MatchCase:= _
False, Orientation:=xlTopToBottom
end_row = endpage * 20
For i = 1 To end_row
x = Fn.Find("給", Cells(i, 2), 1)
Cells(i, 3) = Mid(Cells(i, 2), 3, x - 3)
Next
Range("A:B").Delete
End Sub

2008年3月11日 星期二

Import data from Excel files into Mathematica


If your dataset named test.dat with space delimited has the following contents (Iris dataset).

1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
7 4.6 3.4 1.4 0.3 setosa
8 5.0 3.4 1.5 0.2 setosa
9 4.4 2.9 1.4 0.2 setosa
10 4.9 3.1 1.5 0.1 setosa

You can read this into Mathematica with only one command:

mydata = ReadList["~/iris.txt", {Number, Real, Real, Real, Real, String}] ;

Show the dataset

mydata // TableForm

Read the 2-3 column from the dataset.

iris1 = mydata[[Table[i, {i, 1, 50}], {2, 3}]]; iris2 = mydata[[Table[i, {i, 51, 100}], {2, 3}]]; iris3 = mydata[[Table[i, {i, 101, 150}], {2, 3}]];

Plot the Scatter Plot

Step 1.

Needs["Graphics`MultipleListPlot`"];

Step 2.

MultipleListPlot[{iris1, iris2, iris3}, SymbolShape -> Point, SymbolStyle -> {{PointSize[0.015], Blue}, {PointSize[0.015], Green}, {PointSize[0.015], Red}}, PlotLegend -> {"setosa", "versicolor", "virginica"}, LegendPosition -> {1.07, .3}, LegendSize -> {.3, .3}, PlotRange -> {{4, 8}, {2, 4.5}} ]



2008年3月4日 星期二

Discriminant Analysis Using Quadratic Discriminant Function


In SPSS, there is no subroutine for Quadratic Discriminant Analysis, I write this macro to compute quadratic score and posterior probability. If you have any problem, please let me know.

SET MXLOOP =99999.
MATRIX.
GET DATA/VARIABLES=X1 to Xp/MISSING=OMIT.
GET Group/VARIABLES=Y/MISSING=OMIT.
COMPUTE GMAX=CMAX(Group).
COMPUTE GMIN=CMIN(Group).
COMPUTE NR=NROW(DATA).
COMPUTE NC=NCOL(DATA).
COMPUTE RN=MAKE(GMAX-GMIN+1,1,1).
COMPUTE SSIGMA=MAKE(NC*(GMAX-GMIN+1),NC,0).
COMPUTE PI=4*ARTAN(1).
COMPUTE QDA=MAKE(NR, (GMAX-GMIN)+1,-999).
COMPUTE QDAPOST=MAKE(NR, 2*(GMAX-GMIN)+2,-999).
COMPUTE TEMP2=0.
LOOP I=GMIN TO GMAX.
COMPUTE TEMP1=0.
LOOP J=1 TO NR.
DO IF (Group(J)=I).
COMPUTE TEMP1=TEMP1+1.
END IF.
END LOOP.
COMPUTE TEMPDATA=MAKE(TEMP1,NC,999).
LOOP K=1 TO TEMP1.
COMPUTE TEMPDATA(K,:)=DATA(K+TEMP2,:).
END LOOP.
COMPUTE PG=NROW(TEMPDATA)/NR.
COMPUTE TEMP2=TEMP1+TEMP2.
COMPUTE MEAN=T(CSUM(TEMPDATA)/NROW(TEMPDATA)).
COMPUTE SIGMA=(SSCP(TEMPDATA)-NROW(TEMPDATA)*MEAN*T(MEAN))/(NROW(TEMPDATA)-1).
PRINT SIGMA.
LOOP U=1 TO NC.
COMPUTE SSIGMA(4*(I-1)+U,:)=SIGMA(U,:).
END LOOP.
LOOP V=1 TO NR.
COMPUTE XX=T(DATA(V,:)).
COMPUTE QD=TEMP1/NR*(2*PI)&**(-1*NC/2)*DET(SIGMA)&**(-0.5)*EXP(-0.5*T(XX-MEAN)*INV(SIGMA)*(XX-MEAN)).
COMPUTE QDA(V,I)=LN(QD)+(NC/2)*LN(2*PI).
COMPUTE QDAPOST(V,I)=LN(QD)+(NC/2)*LN(2*PI).
END LOOP.
END LOOP.
LOOP W= 1 TO NC.
LOOP X=1 TO NR.
COMPUTE QDAPOST(X,GMAX-GMIN+1+W)=QDA(X,W)/RSUM(QDA(X,:)).
END LOOP.
END LOOP.
LOOP X=1 TO NR.
LOOP GPRED= 1 TO GMAX-GMIN+1.
DO IF (QDAPOST(X,GPRED)= RMAX(QDA(X,:))).
COMPUTE QDAPOST(X,2*(GMAX-GMIN)+3)=GPRED.
END IF.
END LOOP.
END LOOP.
PRINT QDAPOST.
END MATRIX.