[R] For-loop dummy variables?
Bill.Venables at csiro.au
Bill.Venables at csiro.au
Tue Oct 19 08:31:30 CEST 2010
you might try
dummy <- with(cleary,
cbind(B4 = as.numeric(D1 == 4),
B6 = as.numeric(D1 == 6),
B7 = as.numeric(D1 == 7)))
and do it all in one go.
___
to fix up your apporach you need to use
if(cleary$D1[i] == 4) dummy[i] <- 1 else dummy[i] <- 0
but this is a very clumsy and slow way of going about it.
-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of gravityflyer
Sent: Tuesday, 19 October 2010 1:24 PM
To: r-help at r-project.org
Subject: [R] For-loop dummy variables?
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