Create several dummy variables from one string variable

前端 未结 4 2017
暗喜
暗喜 2020-12-21 11:30

I\'ve tried pretty much everything from this similar question, but I can\'t get the results everyone else seems to be getting. This is my problem:

I have a data fram

4条回答
  •  执念已碎
    2020-12-21 12:09

    You could try mtabulate from qdapTools

    library(qdapTools)
    res <- mtabulate(strsplit(as.character(profs$teaches), ', '))
    colnames(res) <- paste0('teaches', colnames(res))
    res
    #    teaches1st teaches2nd teaches3rd
    #1          1          0          0
    #2          1          1          0
    #3          0          1          1
    #4          1          1          1
    

    Or using stringi

    library(stringi)
    (vapply(c('1st', '2nd', '3rd'), stri_detect_fixed, logical(4L), 
                              str=profs$teaches))+0L
    #     1st 2nd 3rd
    #[1,]   1   0   0
    #[2,]   1   1   0
    #[3,]   0   1   1
    #[4,]   1   1   1
    

提交回复
热议问题