Thursday, November 19, 2015

Getting Data via twitteR

Source

R package twitteR (by Jeff Gentry)

The simplest and quickest way to get data from twitter is by using the
functions of the R package twitteR (check twitteR vignette for more info)
Some (but not all) of the things you can get with twitteR
public tweets
trending topics
tweets containing a given hashtag
tweets containing a given word / term
tweets from a given user

Let's see different examplesStart: First we need to load the package twitteR
(remember to install it first!)

Wednesday, November 18, 2015

Hashtag là gì? Cách sử dụng Hashtag trên Mạng xã hội

Đã từ lâu, dấu # đã xuất hiện nhưng nó chỉ là một kí tự bình thường và đơn giản. Thế nhưng sau khi dấu # xuất hiện trên Twitter thì nó đã trở thành một trong nhưng biểu tượng được rất nhiều người sử dụng khi online. Và gần đây kí tự này đã phổ biến trên rất nhiều trang xã hội khác không riêng gì Twitter như Instagram, Pinterest, Google+, Youtube hay là Facebook. Đó chính là hashtag.

Ban đầu, với những người mới dùng mạng xã hội, việc sử dụng những dấu # để tag dường như là một việc làm phiền phức và rối rắm, không mang lại tác dụng gì. Thế nhưng nếu bạn hiểu rõ mục đích và học cách sử dụng chúng thì những hashtag lại là một công cụ vô cùng hiệu quả giúp bạn thu hút những khách hàng mục tiêu và tăng khả năng nhận diện thương hiệu của bạn.

Hãy cùng Siêu Web tìm hiểu xem hashtag là gì, sức mạnh của nó như thế nào cũng như làm thế nào để phát huy hiệu quả của nó nhé.

VẬY HASHTAG LÀ GÌ ?

Hashtag là một từ hoặc một chuỗi các kí tự viết liền nhau được đặt sau dấu thăng (#) mà mọi người sử dụng trên mạng xã hội. Hashtag sẽ giúp cho nội dung các bài đăng của bạn dễ dàng tới được với những người có chung mối quan tâm, thậm chí họ không theo dõi hay là người đã thích trang của bạn.

Ví dụ, bạn là một fan của Apple và bạn đang có ý định mua một chiếc iPhone 5s, khi bạn đánh từ khóa “#iPhone5s” trên thanh tìm kiếm ở bất kì mạng xã hội nào cũng sẽ mở ra một nguồn thông tin chuyên dụng liên quan tới tất cả những cập nhật mới nhất của iPhone5s, khuyến mại, bàn luận hay những cách hack…



Kết quả hiển thị là tất cả những bài đăng được tổng hợp từ mọi người trên mạng xã hội đó đã đăng lên với cụm “#iPhone5s”. Các hashtag này sẽ hiển thị như là các đường link trên bài đăng, và khi người dùng có thể click chuột vào sẽ hiện ra rất nhiều thông tin có liên quan mà những người dùng khác đã sử dụng cùng 1 loại hashtag.

CÁC DOANH NGHIỆP, SHOP ONLINE CÓ THỂ SỬ DỤNG #HASHTAG ĐỂ QUẢNG BÁ THƯƠNG HIỆU CỦA MÌNH NHƯ THẾ NÀO?

Giả sử thông tin trên mạng xã hội của bạn để chế độ public (ai cũng có thể nhìn thấy), và bạn sử dụng hashtag để những bài đăng của bạn tới được với những người có cùng quan tâm với bạn. Như thế những bài đăng của bạn không những hiển thị bởi những người đang theo dõi bạn hay fan của bạn nữa mà những nội dung này có thể đến được với rất nhiều người khác, những người chưa biết tới bạn nhưng lại có mối quan tâm tới những đề tài tương tự. Việc chọn lựa một hashtag phù hợp có thể giúp bạn tăng độ phù cho các bài đăng của mình trên mạng xã hội tới hàng nghìn khách hàng tiềm năng.
CÁCH TẠO MỘT HASHTAG HIỆU QUẢ

Để tạo một hashtag, tất cả bạn cần làm chỉ là thêm một dấu # trước từ khóa hoặc cụm từ khóa bạn muốn đánh dấu. Bạn có thể chèn hashtag ở bất kì đâu trên bài đăng của mình: đầu, giữa hay cuối bài đăng. Một vài người thích để hashtag ở giữa những bài đăng của họ, trong khi một số khác lại thích chèn vào cuối. Chèn ở đâu không thành vấn đề, miễn là bạn chèn vào đúng từ khóa hoặc cụm từ khóa có liên quan là được.

Bạn có thể chèn Hashtag vào bất kì vị trí nào



Những hashtag sẽ phát huy tác dụng khi được sử dụng một cách thông minh, hiệu quả. Những bài đăng lộn xộn với rất nhiều hashtag hay những hashtag dài dằng dặc (ví dụ như #hashtagdaisekhongmanglaihieuqua) chắc chắn sẽ không thu hút được sự quan tâm của khách hàng. Độ dài các cụm từ cho 1 hashtag dùng trên Twitter nhiều nhất là 2 hoặc 3 từ, còn trên Instagram là 5. Hãy luôn ghi nhớ sử dụng những hashtag ngắn gọn, độc đáo và có liên quan tới chủ đề mà bạn nhắc tới, đặc biệt là sản phẩm và dịch vụ của mình.

LOẠI HASHTAG THÀNH CÔNG TRÊN MẠNG XÃ HỘI
1. NỘI DUNG CỦA HASHTAG

Nếu bạn tạo một hashtag hoàn toàn mới, đầu tiên hãy cân nhắc sử dụng những hashtag nào có liên quan tới thương hiệu, sản phẩm và dịch vụ của bạn. Nội dung của hashtag sẽ ảnh hưởng rất lớn tới việc nhận diện thương hiệu của bạn với những khách hàng tiềm năng trên nền tảng mạng xã hội, những người hầu như chưa biết tới bạn.



Ví dụ như thương hiệu của bạn sắp tổ chức một sự kiện ở Hà Nội, bạn có thể sử dụng hashtag #hanoi để tất cả những người tìm kiếm hashtag này có thể biết đến sự kiện đó. Thật tiện lợi phải không nào?
2. NHỮNG HASHTAG THEO XU HƯỚNG

Một cách tốt để thúc đẩy việc nhận diện thương hiệu của bạn chính là việc sử dụng những hashtag đã có sẵn, những hashtag mà đang được sử dụng phổ biến bởi hàng triệu người dùng. Đấy chính là những hashtag theo xu hướng.

Ví dụ như ngày lễ Halloween, có rất nhiều thương hiệu và công ty lên chiến dịch cho ngày lễ này và tận dụng Hashtag để quảng bá chương trình của họ. Một đợt giảm giá chẳng hạn.



Trước khi bạn sử dụng hashtag cho một chủ đề hot nào đó, bạn cần nhớ đặt mình vào vị trí của khách hàng để xem những bài đăng của bạn trên mạng xã hội liệu có cung cấp thêm giá trị, thêm thông tin vào những cái đã có sẵn hay không. Nếu bài đăng của bạn không thêm giá trị mới nào thì sẽ dễ bị phớt lờ và bị lãng quên giữa rất nhiều bài đăng khác. Tuy nhiên, nếu như bài đăng của bạn cung cấp nhiều thông tin, giá trị mới, hài hước hơn thì rất có thể sẽ được chính những người đã dùng chia sẻ lại và cứ như thế sẽ tạo nên một hiệu ứng rất tốt, bài đăng của bạn sẽ đến được với nhiều người hơn và đương nhiên thương hiệu của bạn cũng vậy.
3. NHỮNG HASHTAG THƯƠNG HIỆU CỤ THỂ

Như đã nói ở trên, vấn đề sử dụng những hashtag chung chung, phổ biến là bài đăng của bạn có thể bị lãng quên giữa rất nhiều bài đăng có cùng chủ đề, cùng hashtag. Vì thế, việc tạo ra một hashtag riêng đặc trưng cho công ty hay cửa hàng của bạn là điều cần thiết. Những hashtag này có thể được sử dụng cho cả thương hiệu của bạn, website bán hàngcủa bạn hay một sự kiện quảng bá, các cuộc thi hay các chương trình tiếp thị.

Ví dụ, nhân ngày kỉ niệm lần thứ 100 của mình, thương hiệu Oreo đã tạo một hashtag đặc biệt là #oreomoment (khoảnh khắc cùng oreo) để khuyến khích người tiêu dùng chia sẻ những khoảnh khắc tuyệt vời của họ với sản phẩm Oreo.



Hashtag này đã trở nên rất phổ biến và thu hút được sự quan tâm cũng như tham gia của rất nhiều người tiêu dùng. Chẳng bao lâu sau, #oreomoment đã trở thành một hashtag phổ biến được rất nhiều người (thậm chí là các công ty khác) sử dụng. Một hashtag thương hiệu tốt

Một hashtag thể hiện thương hiệu là hashtag độc quyền, chưa có thương hiệu nào sử dụng giống như thế. Hãy đảm bảo tính độc đáo và dễ nhớ cho hashtag mà bạn tạo ra. Với những thương hiệu chung, bạn nên sử dụng một phương châm hay slogan ngắn gọn. Khi tạo một hashtag để tiếp thị thương hiệu, hãy đảm bảo rằng bạn đang thôi thúc người dùng để sử dụng sản phẩm và dịch vụ đó.

Ví dụ, bạn có thể thu hút người dùng đọc bài đăng của bạn trên website công ty thông qua các hashtag riêng về chương trình mà bạn đang chạy để có cơ hội nhận những phiếu giảm giá hay giành một giải thưởng nào đó. Và đổi lại, doanh nghiệp, cửa hàng của bạn sẽ tăng được lợi nhuận từ việc thu hút được một lượng lớn khách hàng.

Vậy bạn còn chần chừ gì nữa mà không bắt đầu tận dụng sức mạnh của những hashtag này để mở rộng phạm vị nhận diện thương hiệu của bạn tới những khách hàng tiềm năng của mình ngay bây giờ!

Tuesday, November 10, 2015

Coefficient logit regression meaning

This page shows an example of logistic regression regression analysis with footnotes explaining the output.  These data were collected on 200 high schools students and are scores on various tests, including science, math, reading and social studies (socst).  The variable female is a dichotomous variable coded 1 if the student was female and 0 if male.
Because we do not have a suitable dichotomous variable to use as our dependent variable, we will create one (which we will call honcomp, for honors composition) based on the continuous variable write.  We do not advocate making dichotomous variables out of continuous variables; rather, we do this here only for purposes of this illustration.
use http://www.ats.ucla.edu/stat/data/hsb2, clear

generate honcomp = (write >=60)
logit honcomp female read science
Iteration 0:   log likelihood = -115.64441
Iteration 1:   log likelihood = -84.558481
Iteration 2:   log likelihood = -80.491449
Iteration 3:   log likelihood = -80.123052
Iteration 4:   log likelihood = -80.118181
Iteration 5:   log likelihood =  -80.11818

Logit estimates                              Number of obs   =        200
                                             LR chi2(3)      =      71.05
                                             Prob > chi2     =     0.0000
Log likelihood =  -80.11818                  Pseudo R2       =     0.3072

-------------------------------------------------------------------------
   honcomp |      Coef.   Std. Err.      z   P>|z|   [95% Conf. Interval]
-----------+-------------------------------------------------------------
    female |   1.482498   .4473993     3.31  0.001   .6056111    2.359384
      read |   .1035361   .0257662     4.02  0.000   .0530354    .1540369
   science |   .0947902   .0304537     3.11  0.002    .035102    .1544784
     _cons |   -12.7772    1.97586    -6.47  0.000  -16.64982   -8.904589
-------------------------------------------------------------------------

Iteration Log

Iteration 0:   log likelihood = -115.64441
Iteration 1:   log likelihood = -84.558481
Iteration 2:   log likelihood = -80.491449
Iteration 3:   log likelihood = -80.123052
Iteration 4:   log likelihood = -80.118181
Iteration 5:a  log likelihood = -80.11818
a.  This is a listing of the log likelihoods at each iteration.  (Remember that logistic regression uses maximum likelihood, which is an iterative procedure.)  The first iteration (called iteration 0) is the log likelihood of the "null" or "empty" model; that is, a model with no predictors.  At the next iteration, the predictor(s) are included in the model.  At each iteration, the log likelihood increases because the goal is to maximize the log likelihood.  When the difference between successive iterations is very small,  the model is said to have "converged", the iterating is stopped and the results are displayed.  For more information on this process, see Regression Models for Categorical and Limited Dependent Variables by J. Scott Long.

Model Summary

Logit estimates                               Number of obsc   =        200
                                              LR chi2(3)d      =      71.05
                                              Prob > chi2e     =     0.0000
Log likelihood =  -80.11818b                  Pseudo R2f       =     0.3072
b.  Log likelihood - This is the log likelihood of the final model.  The value -80.11818 has no meaning in and of itself; rather, this number can be used to help compare nested models.
c.  Number of obs - This is the number of observations that were used in the analysis.  This number may be smaller than the total number of observations in your data set if you have missing values for any of the variables used in the logistic regression.  Stata uses a listwise deletion by default, which means that if there is a missing value for any variable in the logistic regression, the entire case will be excluded from the analysis.
d.  LR chi2(3) - This is the likelihood ratio (LR) chi-square test.  The likelihood chi-square test statistic can be calculated by hand as 2*(115.64441 - 80.11818) = 71.05.  This is minus two (i.e., -2) times the difference between the starting and ending log likelihood.  The number in the parenthesis indicates the number of degrees of freedom.  In this model, there are three predictors, so there are three degrees of freedom.
e.  Prob > chi2 - This is the probability of obtaining the chi-square statistic given that the null hypothesis is true.  In other words, this is the probability of obtaining this chi-square statistic (71.05) if there is in fact no effect of the independent variables, taken together, on the dependent variable.  This is, of course, the p-value, which is compared to a critical value, perhaps .05 or .01 to determine if the overall model is statistically significant.  In this case, the model is statistically significant because the p-value is less than .000.
f.  Pseudo R2 - This is the pseudo R-squared.  Logistic regression does not have an equivalent to the R-squared that is found in OLS regression; however, many people have tried to come up with one.  There are a wide variety of pseudo-R-square statistics.  Because this statistic does not mean what R-square means in OLS regression (the proportion of variance explained by the predictors), we suggest interpreting this statistic with great caution.

Parameter Estimates

-------------------------------------------------------------------------
   honcompg|     Coef.h  Std. Err.i     zj  P>|z|j   [95% Conf. Interval]k
-----------+-------------------------------------------------------------
    female |   1.482498   .4473993     3.31  0.001   .6056111    2.359384
      read |   .1035361   .0257662     4.02  0.000   .0530354    .1540369
   science |   .0947902   .0304537     3.11  0.002    .035102    .1544784
     _cons |   -12.7772    1.97586    -6.47  0.000   -16.64982   -8.90459
-------------------------------------------------------------------------
g.  honcomp - This is the dependent variable in our logistic regression.  The variables listed below it are the independent variables.
h.  Coef. - These are the values for the logistic regression equation for predicting the dependent variable from the independent variable.  They are in log-odds units.  Similar to OLS regression, the prediction equation is
log(p/1-p) = b0 + b1*female + b2*read + b3*science
where p is the probability of being in honors composition.  Expressed in terms of the variables used in this example, the logistic regression equation is
log(p/1-p) = -12.7772 + 1.482498*female + .1035361*read + 0947902*science
These estimates tell you about the relationship between the independent variables and the dependent variable, where the dependent variable is on the logit scale.  These estimates tell the amount of increase in the predicted log odds of honcomp = 1 that would be predicted by a 1 unit increase in the predictor, holding all other predictors constant.  Note: For the independent variables which are not significant, the coefficients are not significantly different from 0, which should be taken into account when interpreting the coefficients.  (See the columns with the z-values and p-values regarding testing whether the coefficients are statistically significant).  Because these coefficients are in log-odds units, they are often difficult to interpret, so they are often converted into odds ratios.  You can do this by hand by exponentiating the coefficient, or by using the or option with logit command, or by using the logistic command.
  female - The coefficient (or parameter estimate) for the variable female is 1.482498.  This means that for a one-unit increase in female (in other words, going from male to female), we expect a 1.482498 increase in the log-odds of the dependent variable honcomp, holding all other independent variables constant.
  read - For every one-unit increase in reading score (so, for every additional point on the reading test), we expect a .1035361 increase in the log-odds ofhoncomp, holding all other independent variables constant.
  science - For every one-unit increase in science score, we expect a .0947902 increase in the log-odds of honcomp, holding all other independent variables constant.
  constant - This is the expected value of the log-odds of honcomp when all of the predictor variables equal zero.  In most cases, this is not interesting.  Also, oftentimes zero is not a realistic value for a variable to take.
i.  Std. Err. - These are the standard errors associated with the coefficients.  The standard error is used for testing whether the parameter is significantly different from 0; by dividing the parameter estimate by the standard error you obtain a z-value (see the column with z-values and p-values).  The standard errors can also be used to form a confidence interval for the parameter, as shown in the last two columns of this table.
j.  z and P>|z| - These columns provide the z-value and 2-tailed p-value used in testing the null hypothesis that the coefficient (parameter) is 0.   If you use a 2-tailed test, then you would compare each p-value to your preselected value of alpha.  Coefficients having p-values less than alpha are statistically significant.  For example, if you chose alpha to be 0.05, coefficients having a p-value of 0.05 or less would be statistically significant (i.e., you can reject the null hypothesis and say that the coefficient is significantly different from 0).   If you use a 1-tailed test (i.e., you predict that the parameter will go in a particular direction), then you can divide the p-value by 2 before comparing it to your preselected alpha level.  With a 2-tailed test and alpha of 0.05, you may reject the null hypothesis that the coefficient for female is equal to 0.  The coefficient of 1.482498 is significantly greater than 0.
  The coefficient for read is .1035361 significantly different from 0 using alpha of 0.05 because its p-value is 0.000, which is smaller than 0.05.
  The coefficient for science is .0947902 significantly different from 0 using alpha of 0.05 because its p-value is 0.000, which is smaller than 0.05.
k. [95% Conf. Interval] - This shows a 95% confidence interval for the coefficient.  This is very useful as it helps you understand how high and how low the actual population value of the parameter might be.  The confidence intervals are related to the p-values such that the coefficient will not be statistically significant if the confidence interval includes 0. 

Odds Ratios

In this next example, we will illustrate the interpretation of odds ratios.  We will use the logistic command so that we see the odds ratios instead of the coefficients.  In this example, we will simplify our model so that we have only one predictor, the binary variable female.  Before we run the logistic regression, we will use the tab command to obtain a crosstab of the two variables.
tab female honcomp
           |        honcomp
    female |         0          1 |     Total
-----------+----------------------+----------
      male |        73         18 |        91 
    female |        74         35 |       109 
-----------+----------------------+----------
     Total |       147         53 |       200 
If we divide the number of males who are in honors composition, 18, by the number of males who are not in honors composition, 73, we get the odds of being in honors composition for males, 18/73 = .24657534.  If we do the same thing for females, we get 35/74 = .47297297.  To get the odds ratio, which is the ratio of the two odds that we have just calculated, we get .47297297/.24657534 = 1.9181682.  As we can see in the output below, this is exactly the odds ratio we obtain from the logistic command.  The thing to remember here is that you want the group coded as 1 over the group coded as 0, so honcomp=1/honcomp=0 for both males and females, and then the odds for females/odds for males, because the females are coded as 1.
With regard to the 95% confidence interval, we do not want this to include the value of 1.  When we were considering the coefficients, we did not want the confidence interval to include 0.  If we exponentiate 0, we get 1 (exp(0) = 1).  Hence, this is two ways of saying the same thing.  As you can see, the 95% confidence interval includes 1; hence, the odds ratio is not statistically significant.  Because the lower bound of the 95% confidence interval is so close to 1, the p-value is very close to .05.
There are a few other things to note about the output below.  The first is that although we have only one predictor variable, the test for the odds ratio does not match with the overall test of the model.  This is because the z statistic is actually the result of a Wald chi-square test, while the test of the overall model is a likelihood ratio chi-square.  While these two types of chi-square tests are asymptotically equivalent, in small samples they can differ, as they do here.  Also, we have the unfortunate situation in which the results of the two tests give different conclusions.  This does not happen very often.  In a situation like this, it is difficult to know what to conclude.  One might consider the power, or one might decide if an odds ratio of this magnitude is important from a clinical or practical standpoint.
logistic honcomp female 
Logistic regression                        Number of obs   =        200
                                           LR chi2(1)      =       3.94
                                           Prob > chi2     =     0.0473
Log likelihood =  -113.6769                Pseudo R2       =     0.0170

-------------------------------------------------------------------------
   honcomp | Odds Ratio   Std. Err.      z    P>|z|  [95% Conf. Interval]
-----------+-------------------------------------------------------------
    female |   1.918168   .6400451     1.95   0.051  .9973827    3.689024
-------------------------------------------------------------------------

Source

Monday, November 9, 2015

Oaxaca with R

setwd ("F:/Dropbox/R/")
#install.packages("oaxaca")
require("oaxaca")

# set random seed
set.seed(08544)
# load data set of Hispanic workers in Chicago
data("chicago")
# perform Blinder-Oaxaca Decomposition:
# explain differences in log real wages across native and foreign-born groups
results <- oaxaca(ln.real.wage ~ age + female + LTHS + some.college +
college + advanced.degree | foreign.born,
data = chicago, R = 50)
results$n
results$y
results$threefold$overall
# plot results of the threefold decomposition, variable-by-variable
# only include educational variables
# decomposition components along the left side of the plot
plot(results, component.left = TRUE,
     variables = c("LTHS", "some.college", "college", "advanced.degree"),
     variable.labels = c("LTHS" = "less than high school",
      "some.college" = "some college",
       "advanced.degree" = "advanced degree"))
plot(results, components = c("endowments","coefficients"))
# plot results of the twofold decomposition (overall results)
# equal weight for Group A and B in reference coefficient determinantion (weight = 0.5)
# unexplained portion split into A and B
plot(results, decomposition = "twofold", type = "overall",
     weight = 0.5, unexplained.split = TRUE,
     bar.color = c("limegreen", "hotpink", "steelblue"))

results$twofold$overall
plot(results, decomposition = "twofold", weight = -1)
plot(results, decomposition = "twofold", weight = -1,
      unexplained.split = TRUE, components = c("unexplained A",
      "unexplained B"), component.labels = c("unexplained A" =
      "In Favor of Natives", "unexplained B" = "Against the Foreign-Born"),
      variables = c("age", "female", "college"), variable.labels = c("age" =
      "Years of Age", "female" = "Female", "college" = "College Education"))

plot(results, decomposition = "twofold", weight = -1,
    unexplained.split = TRUE, components = c("unexplained A",
    "unexplained B"), component.labels = c("unexplained A" =
    "In Favor of Natives", "unexplained B" = "Against the Foreign-Born"),
    component.left = TRUE, variables = c("age","female","college"),
    variable.labels = c("age" = "Years of Age", "female" = "Female",
    "college" = "College Education"))

#Specifc numerical values of the point estimates of the unexplained discrimination components
#can, of course, be obtained directly from the "oaxaca"-class object:
variables <- c("age", "female", "college")
columns <- c("weight", "coef(unexplained A)", "coef(unexplained B)")
results$twofold$variables[[5]][variables, columns]

Bayesian Model Averaging examples

#
############### Bayesian Model Averaging examples ###############
#
# This script assumes you have worked through all the previous notes from 
# the web page and you have downloaded, installed, and updated all available
# R packages. 

### Upload the SAS SEM Example data ("SEMData.sav") which is SIMULATION DATA.

library(foreign)

exsem <- read.spss("http://www.unt.edu/rss/class/Jon/R_SC/Module10/SEMData.sav", use.value.labels=TRUE, 
  max.value.labels=Inf, to.data.frame=TRUE)

summary(exsem)
head(exsem)

cor(exsem)

# The goal of the this example is to choose the best set of predictor variables for a linear (OLS) prediction 
# model with Extroversion (extro) as the outcome. 

# Basic linear (OLS) regression model. 

reg.1 <- lm(extro~abstruse+agree+block+cognitive+common+cultural+open+physical+series+sets+social+vocab, data=exsem)
summary(reg.1)

# The BMA (Bayesian Model Averaging) package/library was designed specifically to use Bayesian Model 
# Averaging to address the variable selection problem in the context of several types of models (e.g. 
# GLM, LM, and Survival Models. 
 
library(BMA)

# The function for conducting BMA with respect to linear regression is 'bicreg'. 
# The 'bicreg' function requires a matrix of predictor variables as input. 

attach(exsem)
predictors <- as.matrix(cbind(open, agree, social, cognitive, physical, cultural, vocab, abstruse, 
                              block, common, sets, series))
detach(exsem)

# Conduct the BMA using the 'bicreg' function by submitting the matrix of predictors (predictors) 
# and the outcome variable (exsem$extro).

bma1 <- bicreg(predictors, exsem$extro)
summary(bma1)

# Based on the first column of the output we can see that "open", "agree", and "series" are the most 
# important variables; the column 'p!=0' indicates the percentage/probability that the coefficient 
# for a given predictor is NOT zero. We can also see that the first model 'model 1' (which includes 
# only 'open', 'agree', & 'series') is the best because it has the lowest BIC and the largest 
# posterior probability. 

# The 'ols' part of the output (not printed by default) gives a matrix, with each model as a row and 
# each predictor variable as a column; listing the estimated (OLS) coefficient for each variable in 
# a given model. 

bma1$ols

# Likewise, the 'se' part of the output produces a similar matrix, with the standard errors for each 
# coefficient (for each variable/model combination). 

bma1$se

# The 'postmean' part of the output (not printed by default) contains the average posterior coefficient 
# for each predictor. The 'postsd' provides the standard deviation of each average posterior coefficient.

bma1$postmean

bma1$postsd

# The 'which' part of the output (not provided by default) contains a matrix, with each model as a row and 
# each predictor variable as a column; listing whether a variable was included in each model. 

bma1$which

# The BMA package also contains a plot function for displaying the posterior distributions of the 
# coefficients. 

plot(bma1)

# For a complete description of the 'bicreg' function:

help(bicreg)

# Bayesian model averaging can also be conducted when attempting to identify the best set of predictors 
# for a Generalized Linear Model. The 'bic.glm' function is very similar to 'bicreg'; you must 
# supply a matrix or data frame of the independent variables (predictors) and the outcome variable. 
# Results of the following model mirror those above. However, the obvious benefit of the 'bic.glm' function 
# is the ability to specify non-normal error distributions (i.e. non-Gaussian; e.g. binomial).

bma2 <- bic.glm(predictors, exsem$extro, glm.family = "gaussian")
summary(bma2)

# Notice that when specifying "Gaussian" the estimation of the posterior standard 
# deviations is slightly off; therefore, it is best to use 'bicreg' when family = 
# "Gaussian".

bma1$postsd
bma2$postsd

plot(bma2)

# For a complete description of the 'bic.glm' function and its arguments:

help(bic.glm)

### Example of Binomial Logistic Regression using 'bic.glm'.

# Read in the data:

logreg <- read.table("http://www.unt.edu/rss/class/Jon/R_SC/Module9/logreg1.txt",
          header=TRUE, sep="", na.strings="NA", dec=".", strip.white=TRUE)
summary(logreg)

# Create a matrix of the predictor variables.

attach(logreg)
predictors.logist <- as.matrix(cbind(x1,x2,x3,x4))
detach(logreg)

# Run the 'bic.glm' function specifying the binomial family. 

bma2 <- bic.glm(predictors.logist, logreg$y, glm.family = "binomial")
summary(bma2)

plot(bma2)

### Example of Multinomial Logistic Regression using library 'mlogitBMA' and function 'bic.mlogit'.

library(mlogitBMA)

# Read in the data from the web (data is an SPSS.sav file, so the 'foreign' package is necessary). 

library(foreign)
mdata1 <- 
  read.spss("http://www.unt.edu/rss/class/Jon/R_SC/Module9/MultiNomReg.sav", 
  use.value.labels=TRUE, max.value.labels=Inf, to.data.frame=TRUE)
summary(mdata1)

# Apply the 'bic.logit' function; supplying the formula in standard format, choices represent 
# the choices on the outcome variable (i.e. the categories of the outcome). 

mlog.1 <- bic.mlogit(y ~ x1 + x2 + X3, data = mdata1, choices = 1:3)
summary(mlog.1)

# To see all the arguments of the 'bic.mlogit' function 

help(bic.mlogit)



# End; Feb, 2011

source