Skip to content
Back to formatted view

Raw Message

Message-ID: <1051904469.3eb2c9d516257@webmail.fas.harvard.edu>
Date: 2003-05-02T19:41:09Z
From: langensk@fas.harvard.edu
Subject: Creating Dummy Variables with if else phrase

Dear All,

I want to do 52 state dummy variables. In order to make it easier for me, I 
thought of using the below commands. (x is the vector with state variables, 
matrix will correspond to the dummy variables)


x <- c(1,2,NA,4)
matrix <- matrix(0,nrow=4,ncol=4)

for (i in 1:4) {
if (is.real(x[i])) {
matrix[i,x[i]] <- 1 } else {
matrix[i,] <- rep(NA,4)
}
}

This gives me the following matrix:

1  0  0  0
0  1  0  0
0  0  0  0
0  0  0  1

But I want it to look as follows:

1   0  0  0
0   1  0  0
NA NA NA NA
0   0  0  1


I want the forth row to be NA, but it is unchanged, i.e., 0. The second "else" 
phrase does not seem to work, and I cannot see what is wrong.

I would be very grateful for your help.

Regards, Sophie