Search code examples
rdplyrstrsplittidyr

Splitting column of a data.frame into more columns


I want to split the Out column of Test data.frame into columns separating based on blank space. Here is my MWE. I tried separate function from tidyr package and strsplit function from base R but couldn't figured out the problem.

Test <- 
  structure(list(Out = structure(1:2, .Label = c("t1* -0.4815861  0.3190424   0.2309631", 
  "t2*  0.9189246 -0.1998455   0.2499412"), class = "factor")),
   .Names = "Out", row.names = c(NA, -2L), class = "data.frame")


library(dplyr)
library(tidyr)

Test %>% separate(Out, c("A", "B", "C", "D"),  sep = " ")
Error: Values not split into 4 pieces at 1, 2

strsplit(Test$Out,  " ")
Error in strsplit(Test$Out, " ") : non-character argument

Solution

  • try

    Test %>% separate(Out, c("A", "B", "C", "D"),  sep = "\\s+")
    

    which allows for multiple spaces (\\s+).