rtidyr

How do I separate every character in a string in a vector into a column using tidyr


I want to separate each string in the vector into columns but I can't do it!

library(tidyr)  
    library(dplyr)
    df <- data.frame(x = c("abe", "bas", "dds", "eer"))
    df %>% separate(x, c("A", "B", "C"), sep=1)

The output I want looks like this

  A B C
1 a b e
2 b a s
3 d d s
4 e e r

That sep=1 works for 2 characters but doesn't work for 3. I was hoping a regex like sep="." or sep="[a-z]" would work too but it doesn't.

This is probably super easy but I'm new to R. Won't someone please help!


Solution

  • You were quite close with your own solution. Simply add a second position for the sep argument.

    So:

    library(tidyr)  
    library(dplyr)
    df <- data.frame(x = c("abe", "bas", "dds", "eer"))
    df %>% separate(x, c("A", "B", "C"), sep = c(1,2))
    
      A B C
    1 a b e
    2 b a s
    3 d d s
    4 e e r
    

    Since separate() has been superseded, hereby the same solution using the new separate_wider_position() function.

    df %>% 
      separate_wider_position(x, widths = c(A = 1, B = 1,  C = 1) )
    
    # A tibble: 4 × 3
      A     B     C    
      <chr> <chr> <chr>
    1 a     b     e    
    2 b     a     s    
    3 d     d     s    
    4 e     e     r