How to Create a Single Dummy Variable with conditions in multiple columns?

前端 未结 3 1000
执念已碎
执念已碎 2020-12-11 12:56

I am trying to efficiently create a binary dummy variables (1/0) in my data set based on whether or not one or more of 7 variables (col9-15) in the data set take on a specif

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-11 13:06

    apply to the rescue :)

    # this sample data frame is pre-loaded
    mtcars
    
    # test whether any of the values in the
    # 2nd - 5th columns of mtcars equal four..
    
    # save the result into a new vector..
    indicator.col <- 
        apply( 
            mtcars[ , 2:5 ] , 
            1 ,
            FUN = function( x ) max( x == 4 ) 
        )
    
    # ..that quickly binds onto mtcars
    # and bind it with the original mtcars
    mtcars2 <- cbind( mtcars , indicator.col )
    
    # look at your result
    mtcars2
    

提交回复
热议问题