Convert continuous dataframe into binary dataframe in R

后端 未结 2 1455
误落风尘
误落风尘 2021-01-24 23:50

I have the following data frame:

i39<-c(5,3,5,4,4,3)
i38<-c(5,3,5,3,4,1)
i37<-c(5,3,5,3,4,3)
i36<-c(5,4,5,5,4,2)
ndat1<-as.data.frame(cbind(i39,i3         


        
相关标签:
2条回答
  • 2021-01-25 00:02

    With your data set I would just do

    ndat1[] <- +(ndat1 >= 4)
    #   i39 i38 i37 i36
    # 1   1   1   1   1
    # 2   0   0   0   1
    # 3   1   1   1   1
    # 4   1   0   0   1
    # 5   1   1   1   1
    # 6   0   0   0   0
    

    Though a more general solution will be

    ndat1[] <- +(ndat1 == 4 | ndat1 == 5)
    #   i39 i38 i37 i36
    # 1   1   1   1   1
    # 2   0   0   0   1
    # 3   1   1   1   1
    # 4   1   0   0   1
    # 5   1   1   1   1
    # 6   0   0   0   0
    

    Some data.table alternative

    library(data.table)
    setDT(ndat1)[, names(ndat1) := lapply(.SD, function(x) +(x %in% 4:5))]
    

    And I'll to the dplyr guys have fun with mutate_each

    0 讨论(0)
  • 2021-01-25 00:06

    I used the following to solve this issue:

    recode<-function(ndat1){
    ifelse((as.data.frame(ndat1)==4|as.data.frame(ndat1)==5),1,0)
    }
    sum_dc1<-as.data.frame(sapply(as.data.frame(ndat1),recode),drop=FALSE)
    > sum_dc1
      i39 i38 i37 i36
    1   1   1   1   1
    2   0   0   0   1
    3   1   1   1   1
    4   1   0   0   1
    5   1   1   1   1
    6   0   0   0   0
    

    I was just wondering if anyone else had any thoughts, but overall I am satisfied with this way of solving the issue. Thank you.

    0 讨论(0)
提交回复
热议问题