[R] For-loop dummy variables?

Phil Spector spector at stat.berkeley.edu
Tue Oct 19 09:32:09 CEST 2010


I always find R useful to solve problems like this:

   dummy = as.numeric(cleary$D1 %in% c(4,6,7))

If, for some reason you want to use a loop, try

dummy <- matrix(NA, nrow=nrow(cleary), ncol=1)
for (i in 1:length(cleary$D1)){
       if (cleary$D1[i] %in% c(4,6,7)){dummy[i] = 1}
       else {dummy[i] = 0}
       }

When you write a loop, you need to use the loop index
to select the individual value you're working with.


 					- Phil Spector
 					 Statistical Computing Facility
 					 Department of Statistics
 					 UC Berkeley
 					 spector at stat.berkeley.edu


On Mon, 18 Oct 2010, gravityflyer wrote:

>
> Hi everyone,
>
> I've got a dataset with 12,000 observations. One of the variables
> (cleary$D1) is for an individual's country, coded 1 - 15. I'd like to create
> a dummy variable for the Baltic states which are coded 4,6, and 7. In other
> words, as a dummy variable Baltic states would be coded 1, else 0.  I've
> attempted the following for loop:
>
> dummy <- matrix(NA, nrow=nrow(cleary), ncol=1)
> for (i in 1:length(cleary$D1)){
> 	if (cleary$D1 == 4){dummy[i] = 1}
> 	else {dummy[i] = 0}
> 	}
>
> Unfortunately it generates the following error:
>
> 1: In if (cleary$D1 == 4) { ... :
>  the condition has length > 1 and only the first element will be used
>
>
> Another options I've tried is the following:
>
> binary <- vector(length=length(cleary$D1))
> for (i in 1:length(cleary$D1)) {
> 	if (cleary$D1 == 4 | cleary$D1 == 6 | cleary$D1 == 7 ) {binary[i] = 1}
> 	else {binary[i] = 0}
> }
>
> Unfortunately it simply responds with "syntax error".
>
> Any thoughts would be greatly appreciated!
>
>
> -- 
> View this message in context: http://r.789695.n4.nabble.com/For-loop-dummy-variables-tp3001396p3001396.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.
>



More information about the R-help mailing list