Replace logical values (TRUE / FALSE) with numeric (1 / 0)

前端 未结 6 605
傲寒
傲寒 2020-12-03 04:34

I am exporting data from R with the command:

write.table(output,file = "data.raw", na "-9999", sep = "\\t", row.names = FALSE, c         


        
6条回答
  •  感动是毒
    2020-12-03 05:13

    For a data.frame, you could convert all logical columns to numeric with:

    # The data
    set.seed(144)
    dat <- data.frame(V1=1:100,V2=rnorm(100)>0)
    dat$V3 <- dat$V2 == 1
    head(dat)
    #   V1    V2    V3
    # 1  1 FALSE FALSE
    # 2  2  TRUE  TRUE
    # 3  3 FALSE FALSE
    # 4  4 FALSE FALSE
    # 5  5 FALSE FALSE
    # 6  6  TRUE  TRUE
    
    # Convert all to numeric
    cols <- sapply(dat, is.logical)
    dat[,cols] <- lapply(dat[,cols], as.numeric)
    head(dat)
    #   V1 V2 V3
    # 1  1  0  0
    # 2  2  1  1
    # 3  3  0  0
    # 4  4  0  0
    # 5  5  0  0
    # 6  6  1  1
    

    In data.table syntax:

    # Data
    set.seed(144)
    DT = data.table(cbind(1:100,rnorm(100)>0))
    DT[,V3 := V2 == 1]
    DT[,V4 := FALSE]
    head(DT)
    #    V1 V2    V3    V4
    # 1:  1  0 FALSE FALSE
    # 2:  2  1  TRUE FALSE
    # 3:  3  0 FALSE FALSE
    # 4:  4  0 FALSE FALSE
    # 5:  5  0 FALSE FALSE
    # 6:  6  1  TRUE FALSE
    
    # Converting
    (to.replace <- names(which(sapply(DT, is.logical))))
    # [1] "V3" "V4"
    for (var in to.replace) DT[, (var):= as.numeric(get(var))]
    head(DT)
    #    V1 V2 V3 V4
    # 1:  1  0  0  0
    # 2:  2  1  1  0
    # 3:  3  0  0  0
    # 4:  4  0  0  0
    # 5:  5  0  0  0
    # 6:  6  1  1  0
    

提交回复
热议问题