我想模拟逻辑回归的数据,我可以事先指定其解释的方差.看看下面的代码.我模拟了四个自变量,并指定每个logit系数的大小应为log(2)= 0.69.这很好用,解释的方差(我报告Cox和Snell的r2)是0.34.
但是,我需要指定回归系数,使得预先指定的r2将来自回归.因此,如果我想产生一个让我们说的精确到0.1的r2.如何指定系数?我有点挣扎着......
# Create independent variables
sigma.1 <- matrix(c(1,0.25,0.25,0.25,
0.25,1,0.25,0.25,
0.25,0.25,1,0.25,
0.25,0.25,0.25,1),nrow=4,ncol=4)
mu.1 <- rep(0,4)
n.obs <- 500000
library(MASS)
sample1 <- as.data.frame(mvrnorm(n = n.obs, mu.1, sigma.1, empirical=FALSE))
# Create latent continuous response variable
sample1$ystar <- 0 + log(2)*sample1$V1 + log(2)*sample1$V2 + log(2)*sample1$V3 + log(2)*sample1$V4
# Construct binary response variable
sample1$prob <- exp(sample1$ystar) / (1 + exp(sample1$ystar))
sample1$y <- rbinom(n.obs,size=1,prob=sample1$prob)
# Logistic regression
logreg <- glm(y ~ V1 + V2 + V3 + V4, data=sample1, family=binomial)
summary(logreg)
Run Code Online (Sandbox Code Playgroud)
输出是:
Call:
glm(formula …Run Code Online (Sandbox Code Playgroud) 我想用四个预测变量来模拟多元线性回归的数据,我可以自由指定
\n\n我得出了一个满足前两点的解决方案,但基于所有自变量彼此不相关的假设(请参见下面的代码)。为了获得标准化回归系数,我从平均值 = 0 和方差 = 1 的总体变量中进行采样。
\n\n# Specify population variance/covariance of four predictor variables that is sampled from\nsigma.1 <- matrix(c(1,0,0,0, \n 0,1,0,0, \n 0,0,1,0, \n 0,0,0,1),nrow=4,ncol=4)\n# Specify population means of four predictor varialbes that is sampled from \nmu.1 <- rep(0,4) \n\n# Specify sample size, true regression coefficients, and explained variance\nn.obs <- 50000 # to avoid sampling error problems\nintercept <- 0.5\nbeta <- c(0.4, 0.3, 0.25, 0.25)\nr2 <- …Run Code Online (Sandbox Code Playgroud) 我正在努力完成以下任务:我需要从截断的正态分布生成数据。样本均值和标准差应与总体中指定的值完全匹配。这是我到目前为止所拥有的:
mean <- 100
sd <- 5
lower <- 40
upper <- 120
n <- 100
library(msm)
data <- as.numeric(mean+sd*scale(rtnorm(n, lower=40, upper=120)))
Run Code Online (Sandbox Code Playgroud)
创建的样本完全采用总体中指定的平均值和标准差。但有些值超出了预期范围。知道如何解决这个问题吗?我正在考虑切断这些界限之外的所有值,但平均值和标准差不再类似于总体的值。