Re: [R] Creating Dummy Variables with if else phrase

About this list Date view Thread view Subject view Author view Attachment view

From: Achim Zeileis (zeileis@ci.tuwien.ac.at)
Date: Sat 03 May 2003 - 05:49:04 EST


Message-id: <200305021949.h42Jn43b031320@thorin.ci.tuwien.ac.at>

On Friday 02 May 2003 21:41, langensk@fas.harvard.edu wrote:

> 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 don't really understand why you want to create a matrix that way,
but if you want to do it the way described above
  is.real(x[i])
seems to be the wrong function (because x is a real vector in the
example above). If you want to test for NA you should use
  !is.na(x[i])
instead.
Z

> 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
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help


About this list Date view Thread view Subject view Author view Attachment view

This archive was generated by hypermail 2.1.3 : Tue 01 Jul 2003 - 09:11:44 EST