0

If my data resembles this:

  Variable 1   Variable 2   Variable 3
1   Red|Blue      0|1          1|0
2   Blue|Red      1|0          0|1
3   Green|Red     0|1          1|0
4   Yellow|Blue   1|0          0|1

What might I use to separate based on the "|"? Something like this:

 Variable 1   Variable 2   Variable 3
1   Red           0            1
2   Blue          1            0
3   Blue          1            0
4   Red           0            1
5   Green         0            1
6   Red           1            0
7   Yellow        1            0
8   Blue          0            1
1
  • check out tidyr::separate_rows(). E.g., separate_rows(df, everything(), sep = "\\|") Commented Jul 2, 2020 at 18:40

2 Answers 2

3

You can use separate_rows

> df %>% 
   separate_rows(., Variable1, Variable2, Variable3, convert = TRUE)
# A tibble: 8 x 3
  Variable1 Variable2 Variable3
  <chr>         <int>     <int>
1 Red               0         1
2 Blue              1         0
3 Blue              1         0
4 Red               0         1
5 Green             0         1
6 Red               1         0
7 Yellow            1         0
8 Blue              0         1
Sign up to request clarification or add additional context in comments.

Comments

0

We can also use cSplit from splitstackshape

library(splitstackshape)
cSplit(df1, c("Variable1", "Variable2", "Variable3"), sep="|", "long")
#   Variable1 Variable2 Variable3
#1:       Red         0         1
#2:      Blue         1         0
#3:      Blue         1         0
#4:       Red         0         1
#5:     Green         0         1
#6:       Red         1         0
#7:    Yellow         1         0
#8:      Blue         0         1

data

df1 <- structure(list(Variable1 = c("Red|Blue", "Blue|Red", "Green|Red", 
"Yellow|Blue"), Variable2 = c("0|1", "1|0", "0|1", "1|0"), Variable3 = c("1|0", 
"0|1", "1|0", "0|1")), class = "data.frame", row.names = c("1", 
"2", "3", "4"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.