Home > Software engineering >  Split character vector values by fixed delimiter - return data frame with one row for each vector va
Split character vector values by fixed delimiter - return data frame with one row for each vector va

Time:11-21

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

CodePudding user response:

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

CodePudding user response:

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)
  •  Tags:  
  • r
  • Related