2

I have a dataset that has a column which consists of 0 and 1s. Is there a way that I can separate that column into two columns so that one column consists of the 0s and the other 1s?

I tried to used the separate function from tidyverse however, it hasn't worked yet.

Phil
  • 7,287
  • 3
  • 36
  • 66
babygould
  • 29
  • 3
  • 1
    [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 [51] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 [101] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 [151] 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ... The column looks something like this full of 1s and 0 s (int) – babygould Jan 13 '23 at 17:17

2 Answers2

0

We may use split in base R

lst1 <- split(df1$col1, df1$col1)
mx <- max(lengths(lst1))
data.frame(lapply(lst1, `length<-`, mx))

Or if we want to create two columns

library(dplyr)
library(tidyr)
library(data.table)
df1 %>% 
  mutate(rn = rowid(col1), 
   colnm = case_when(col1 == 0 ~ "col1", TRUE ~ "col2")) %>% 
   pivot_wider(names_from = colnm, values_from = col1) %>%
   select(-rn)

-output

# A tibble: 8 × 2
   col1  col2
  <dbl> <dbl>
1     0     1
2     0     1
3     0     1
4     0     1
5     0     1
6     0     1
7     0     1
8     0    NA

data

df1 <- structure(list(col1 = c(0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 
1, 1)), class = "data.frame", row.names = c(NA, -15L))
akrun
  • 874,273
  • 37
  • 540
  • 662
0

A simple ifelse statement could also be used to do this. -

df <- as.data.frame(c(0,0,1,0,1,1,0,0,0,0,0,1,0,0,0,0,1,1,0))

names(df)<-"col1"

df$col_0 <- ifelse(df$col1 == 0, 0, NA)
df$col_1 <- ifelse(df$col1 == 1, 1, NA)

Returns the following result:

> df
   col1 col_0 col_1
1     0     0    NA
2     0     0    NA
3     1    NA     1
4     0     0    NA
5     1    NA     1
6     1    NA     1
7     0     0    NA
8     0     0    NA
9     0     0    NA
10    0     0    NA
11    0     0    NA
12    1    NA     1
13    0     0    NA
14    0     0    NA
15    0     0    NA
16    0     0    NA
17    1    NA     1
18    1    NA     1
19    0     0    NA
sky_megh
  • 135
  • 6