[R] Correlated variables

David L Carlson dcarlson at tamu.edu
Wed Mar 15 19:07:46 CET 2017


You will have to use a for loop if you insist on using control statements such as if-else. You should really read up on the ifelse() function and vectorization in R:

> set.seed(42) # So your results will match these
> n <- 25
> x1 <- rnorm(n, 0, 1)
> x2 <- rnorm(n, 0, 1)
> x3 <- rnorm(n, 0, 1)
> prb <- ifelse(x1 + x2 - x3 > .25, .25, .5)
> prb
 [1] 0.25 0.50 0.50 0.25 0.50 0.50 0.25 0.25 0.25 0.50 0.50 0.25 0.50 0.50
[15] 0.25 0.50 0.50 0.50 0.50 0.50 0.25 0.50 0.25 0.25 0.25
> t <- rbinom(n, 1, prob=prb)
> t
 [1] 0 0 1 0 1 1 0 0 0 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0

?ifelse
?Control
?rbinom

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

-----Original Message-----
From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Art U
Sent: Wednesday, March 15, 2017 9:56 AM
To: r-help at r-project.org
Subject: [R] Correlated variables

Hi,

I'm trying to create binary variable which distribution conditioned on
other variables. That is what I did,

x1=rnorm(n,0,1);
x2=rnorm(n,0,1);
x3=rnorm(n,0,1);
if(x1+x2-x3>0.25){
  t=rbinom(1, 1, prob=0.25)
}else{
  t=rbinom(1, 1, prob=0.5)
}

But I always get this the warning:

Warning message:In if (x1 + x2 - x3 > 0.5) { :
  the condition has length > 1 and only the first element will be used


Can I do this without using function "for"?

Thank you in advance.
Ariel
-- 
*I like to pretend I'm alone*. *Completely alone*. *Maybe post-apocalypse
or plague*... *Whatever*. *No-one left to act normal for. No need to hide
who I really am. It would be... freeing*. *...*

	[[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.



More information about the R-help mailing list