rrbest rrbest - 3 months ago 34
R Question

Split column at multiple-character delimiter in data frame

My question is very similar to the question below, with the added problem that I need to split by a double-space.

Split column at delimiter in data frame

I would like to split this vector into columns.

text <- "first second and second third and third and third fourth"

The result should be four columns reading "first", "second and second", "third and third and third", "fourth"


We can use \\s{2,} to match the pattern of space that are 2 or more in strsplit

v1 <- strsplit(text, "\\s{2,}")[[1]]
#[1] "first"                     "second and second"    
#[3] "third and third and third" "fourth"      

This can be converted to data.frame using as.data.frame.list

setNames(as.data.frame.list(v1), paste0("col", 1:4))