如何将二进制列拆分为两列

时间:2019-06-13 23:29:10

标签: r dplyr tidyr

我正在尝试根据0,1将二进制列拆分为两个单独的列

     account  
row1 0
row2 1
row3 0
row4 1
row5 0
row6 0

     account_0 | account_1 
row1 0         |  
row2           |  1
row3 0         |
row4           |  1
row5 0         |
row6 0         |

尝试使用单独的功能。但它期望分隔符分隔列

test=separate(df, col = account, into = c("account_0","account
-1"), sep = ?) [not sure what to pass for the argument "sep"]

View(test)

有人可以尝试吗?

2 个答案:

答案 0 :(得分:1)

reshape(transform(df,time=account),dir="wide",idvar = "id")
    id account.0 account.1
1 row1         0        NA
2 row2        NA         1
3 row3         0        NA
4 row4        NA         1
5 row5         0        NA
6 row6         0        NA

read.csv(text = sub("(,1)",',\\1',do.call(paste,c(sep=',',df))),fill=T,h=F)
    V1 V2 V3
1 row1  0 NA
2 row2 NA  1
3 row3  0 NA
4 row4 NA  1
5 row5  0 NA
6 row6  0 NA

答案 1 :(得分:0)

假设腾出的单元格是空格,这里的01也是字符。可以使用dplyr完成。您可以使用select选择所需的任何列。     TestData <-fread(“ RowNumber account
    第1行0     第2行1     第3行0     第4行1     第5行0     row6 0“)

TestData %>% mutate(account_0  = ifelse(account == 0, "0"," ")) %>% mutate(account_1  = ifelse(account == 1, "1"," "))

   RowNumber account account_0 account_1
1:      row1       0         0          
2:      row2       1                   1
3:      row3       0         0          
4:      row4       1                   1
5:      row5       0         0          
6:      row6       0         0