Creating categorical variables from mutually exclusive dummy variables

前端 未结 3 1428
忘了有多久
忘了有多久 2021-01-11 23:51

My question regards an elaboration on a previously answered question about combining multiple dummy variables into a single categorical variable.

In the question p

3条回答
  •  伪装坚强ぢ
    2021-01-12 00:19

    I think this function gives you what you need (admittedly, this is a quick hack).

    to_indicator <- function(x, grp)
    {
        apply(tbl, 1,
              function (x)
              {
                  idx <- which(!is.na(x))
                  nm <- names(idx)
                  if (nm %in% grp)
                    x[idx]
                  else
                    NA
              })
    }
    

    And here is it's used with the example data you provide.

    tbl <- read.table(header=TRUE, text="
    conditionA    conditionB    conditionC     conditionD
    NA            1             NA             NA
    1             NA            NA             NA
    NA            NA            1              NA
    NA            NA            NA             1
    NA            2             NA             NA
    2             NA            NA             NA
    NA            NA            2              NA
    NA            NA            NA             2")
    tbl <- data.frame(tbl)
    
    (tbl <- cbind(tbl,
                  factor1=to_indicator(tbl, c("conditionA", "conditionB")),
                  factor2=to_indicator(tbl, c("conditionC", "conditionD"))))
    

提交回复
热议问题