Search code examples
rtransformationdummy-variable

Transform many numerical variables to dummy variables at once


I'm stuck trying to convert a bunch of integer variables (with values from one to 10, plus a few NAs) into the same number of boolean variables, where values<=8 become FALSE, >8 become TRUE, and NAs remain as NAs.

Based on other Q&As around, I tried the following but nothing worked:

TPS <- names(datos[,1:3])
    for(i in TPS) {
     data4[[i]]==NA <- NA
     data4[[i]]<8 <- FALSE
     data4[[i]]>=8 <- TRUE
    }

    TPS <- names(data4[,8:48])
    for(i in TPS) {
      data4[,i]==NA <- NA
      data4[,i]<8 <- FALSE
      data4[,i]>=8 <- TRUE
    }

    TPS <- names(data4[,8:48])
    for(i in TPS) {
      ifelse(data4[,i]<8, FALSE, TRUE)
    }

I know how to do it one variable at a time, but my dataset have 64 variables I have to transform in just 2 different ways, so a procedure to do this in just 2 steps would be extremely useful.


Solution

  • You can just use

     data4[,8:48] >8
    

    The output will be a logical matrix of TRUE/FALSE values and NA (if there are).