-->

Multinom with Matrix of Counts as Response

2019-05-13 07:17发布

问题:

According to the help of multinom, package nnet, "The response should be a factor or a matrix with K columns, which will be interpreted as counts for each of K classes." I tried to use this function in the second case, obtaining an error.

Here is a sample code of what I do:

response  <- matrix(round(runif(200,0,1)*100),ncol=20) # 10x20 matrix of counts
predictor <- runif(10,0,1)
fit1 <- multinom(response ~ predictor)
weights1 <- predict(fit1, newdata = 0.5, "probs")

Here what I obtain:

'newdata' had 1 row but variables found have 10 rows

How can I solve this problem?

Bonus question: I also noticed that we can use multinom with a predictor of factors, e.g. predictor <- factor(c(1,2,2,3,1,2,3,3,1,2)). I cannot understand how this is mathematically possible, given that a multinomial linear logit regression should work only with continuous or dichotomous predictors.

回答1:

The easiest method for obtaining the predictions for a new variable is to define the new data as a data.frame.

Using the sample code

> predict(fit1, newdata = data.frame(predictor = 0.5), type = "probs")
 [1] 0.07231972 0.05604055 0.05932186 0.07318140 0.03980245 0.06785690 0.03951593 0.02663618
 [9] 0.04490844 0.04683919 0.02298260 0.04801870 0.05559221 0.04209283 0.03799946 0.06406533
[17] 0.04509723 0.02197840 0.06686314 0.06888748