Separate string with keeping separator

Viewed 101

I have a datafarme:

ID    Value
1    message "some text"
2    more messages "some more text"

I separate a column in my dataframe in this way:

df <- df  %>%
  separate(Value, c("message", "text"), ' "', remove = TRUE) 

But i get this:

ID    message             text
1    message          some text"
2    more messages    some more text"

Instead of this:

ID    message             text
1    message          "some text"
2    more messages    "some more text"

How could i keep that separator? I also tried this, but makes the same mistake:

df %>% 
  tidyr::extract(col = "Value",
                 into = c("message", "text"),
                 regex = '^(.*?) "(.*?)$', remove = FALSE)
1 Answers

You may use

separate(Value, c("message", "text"), '\\s+(?=")', remove = TRUE) 

See the regex demo.

The \s+(?=") pattern matches 1 or more whitespaces that are immediately followed with a " char.

Alternatively, with extract, you may use

tidyr::extract(col = "Value",
                 into = c("message", "text"),
                 regex = '^([^"]*)\\s(".*)', remove = FALSE)

See the regex demo. The regex means:

  • ^ - start of string
  • ([^"]*) - Group 1 (message): any zero or more chars other than "
  • \s - a whitespace
  • (".*) - Group 2 (text): " and then any zero or more chars other than line break chars as many as possible
Related