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

前端 未结 6 603
傲寒
傲寒 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:23

    As Ted Harding pointed out in the R-help mailing list, one easy way to convert logical objects to numeric is to perform an arithmetic operation on them. Convenient ones would be * 1 and + 0, which will keep the TRUE/FALSE == 1/0 paradigm.

    For your mock data (I've changed the code a bit to use regular R packages and to reduce size):

    df    <- data.frame(cbind(1:10, rnorm(10) > 0))
    df$X3 <- df$X2 == 1
    df$X4 <- df$X2 != 1
    

    The dataset you get has a mixture of numeric and boolean variables:

       X1 X2    X3    X4
    1   1  0 FALSE  TRUE
    2   2  0 FALSE  TRUE
    3   3  1  TRUE FALSE
    4   4  1  TRUE FALSE
    5   5  1  TRUE FALSE
    6   6  0 FALSE  TRUE
    7   7  0 FALSE  TRUE
    8   8  1  TRUE FALSE
    9   9  0 FALSE  TRUE
    10 10  1  TRUE FALSE
    

    Now let

    df2 <- 1 * df
    

    (If your dataset contains character or factor variables, you will need to apply this operation to a subset of df filtering out those variables)

    df2 is equal to

       X1 X2 X3 X4
    1   1  0  0  1
    2   2  0  0  1
    3   3  1  1  0
    4   4  1  1  0
    5   5  1  1  0
    6   6  0  0  1
    7   7  0  0  1
    8   8  1  1  0
    9   9  0  0  1
    10 10  1  1  0
    

    Which is 100% numeric, as str(df2) will show you.

    Now you can safely export df2 to your other program.

提交回复
热议问题