Split character vector values by fixed delimiter - return data frame with one row for each vector value

Viewed 43

The delimiter is present in all vector values, and only once, thus each vector value should result in exactly one pair and the result should be a two column data frame.

I am not unhappy about my solution, but wondered if there might be cool functions around that make this easier. Open for any package, but base R preferred.

test <- rep("a,b", 5)

# expected result
data.frame(t(do.call(cbind, strsplit(test, ","))))
#>   X1 X2
#> 1  a  b
#> 2  a  b
#> 3  a  b
#> 4  a  b
#> 5  a  b
2 Answers

You can use tidyr::separate().

test <- data.frame(x = rep("a,b", 5))
separate(test,x, c("X1","X2"))
#>   X1 X2
#> 1  a  b
#> 2  a  b
#> 3  a  b
#> 4  a  b
#> 5  a  b

You can use extract:

library(tidyr)

data.frame(test) %>%
  extract(col = test, 
          into = c("X1", "X2"),
          regex = "(.),(.)")
 X1 X2
1 a  b
2 a  b
3 a  b
4 a  b
5 a  b

Data:

test <- rep("a,b", 5)
Related