下面是一个变量的多次测试代码(参见):
## read data
library(foreign)
ml <- read.dta("http://www.ats.ucla.edu/stat/data/hsbdemo.dta")
## define the reference group
ml$prog2 <- relevel(ml$prog, ref = "academic")
## starting to do the test, here is one result
test <- multinom(prog2 ~ ses, data = ml)
summary(test) ## need to display this
### caculate the z value
z <- summary(test)$coefficients/summary(test)$standard.errors
z ## this output need to display
### caculate the p value
# 2-tailed z test
p <- (1 - pnorm(abs(z), 0, 1)) * 2
p ## this output need to display.
由于在日期集中有多个变量(例如:“female”“ses”“schtyp”),我尝试编写一个循环来生成上面指出的所有必需输出,使用下面的代码:
## read the data
ml <- read.dta("http://www.ats.ucla.edu/stat/data/hsbdemo.dta")
ml$prog2 <- relevel(ml$prog, ref = "academic")
## Here define the varlist
varlist <- names(ml)[2:4]
varlist
### define the for loop to do the analysis for the three varible defined above
models <- lapply(varlist, function(x) {
multinom(substitute(prog2 ~ i, list(i = as.name(x))), data = ml)
})
models
通过这样做,它只能显示第一个所需输出的输出,如何改进这个还包括另外两个输出?或者我们在函数中添加另一个函数?
答案 0 :(得分:1)
您可以使用列表从函数中返回多个项目。但是,当你在拟合模型上调用multinom
时,nnet
(我假设来自summary()
包)尝试评估其参数时,看起来有些奇怪。我还将您的lappy
更改为Map
,以便返回命名列表。
varlist
[1] "female" "ses" "schtyp"
library(nnet)
models <- Map(function(x) {
f <- substitute(prog2 ~ i, list(i = as.name(x)))
mm <- eval(bquote(multinom(.(f), data = ml)))
ms <- summary(mm)
z <- ms$coefficients/ms$standard.errors
p <- (1 - pnorm(abs(z), 0, 1)) * 2
list(ms , z, p)
}, varlist)
models
这会返回一个嵌套列表
model$female[[1]] #summary
model$female[[2]] #z-values
model$female[[3]] #p-values
其余系数也是如此。