# [R] creating multivariate normal random variables

David Carlson dcarlson at tamu.edu
Thu May 9 22:03:19 CEST 2013

```What is rbern()? Assuming it should be rbinom(), this can be simplified:

> set.seed(42)
> y <- rbinom(100, 1, .5)
> x.1 <- rnorm(100, .02, 1)
> x.2 <- rnorm(100, .07, 1)
> x <- ifelse(y==0, x.1, x.2)
>
> glm.out = glm(formula = y ~ x, family = binomial(logit))
> summary(glm.out)

Call:
glm(formula = y ~ x, family = binomial(logit))

Deviance Residuals:
Min       1Q   Median       3Q      Max
-1.3878  -1.2401   0.9768   1.1012   1.2116

Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept)   0.2078     0.2019   1.029    0.303
x             0.1719     0.2197   0.783    0.434

(Dispersion parameter for binomial family taken to be 1)

Null deviance: 137.63  on 99  degrees of freedom
Residual deviance: 137.01  on 98  degrees of freedom
AIC: 141.01

Number of Fisher Scoring iterations: 4

> hat.beta.L <- coef(glm.out)
> hat.beta.L
(Intercept)           x
0.2078484   0.1719438

-------------------------------------
David L Carlson
Associate Professor of Anthropology
Texas A&M University
College Station, TX 77840-4352

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of asdf1234
Sent: Thursday, May 9, 2013 9:48 AM
To: r-help at r-project.org
Subject: [R] creating multivariate normal random variables

Dear R experts,

I am trying to create a dataset, with one dependent binomial and one independen (normal) variable.
I have the condition that my x should be created in the following way:

if y=0 my x should have mean=0.2 and variance=1 if y=1 my x should have mean=0.7 and variance=1 Furthermore, my y is chosen with a prbability of 0.5

I tried it with the following expression:

n <- 1
prob <- 0.5
result.y <- vector("list",100)
result.X <- vector("list",100)
for (i in 1:100)
{
y <- rbern(n, prob)
X <- if(y==0){X <- rnorm(n, mean=0.2, sd=1)}else{X <- mvrnorm(n, mean=0.7, sd=1)}
result.y[[i]] <- y
result.X[[i]] <- X
}
y <- result.y
X <- result.X

matrix <- cbind(result.y, result.X)
View(matrix)

However, when I try to run a logistic regression

glm.out = glm(formula = y ~ X, family = binomial(logit))
summary(glm.out)
hat.beta.L <- coef(glm.out)

I get the error massage

Fehler in model.frame.default(formula = y ~ X, drop.unused.levels = TRUE) :
ungültiger Typ (list) für die Variable 'y'

Does someone know what I am doing wrong?
Thank you very much for your help, I really appreciate it.

--
View this message in context: http://r.789695.n4.nabble.com/creating-multivariate-normal-random-variables-tp4666678.html
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

```