useRj
useRj

Reputation: 1312

Split column depending on several patterns in R

Some data processing work I needs to do is split a column depending on several words. For the sake of simplicity let's say I have only two words (after and before)

Example data

data <- structure (list(author=c("joe","mack","rick"),options=c("bike before run","car after bike","bus after bike")), class= "data.frame", row.names=c(NA,-3L))

output:

author  new1   new2
joe     bike   run
mack    car    bike
rick    bus    bike

Tried using tidyr to no avail

data %>% tidyr::separate(options, into=c("new1","new2"),sep="after|before")

Upvotes: 0

Views: 214

Answers (1)

Marcos P&#233;rez
Marcos P&#233;rez

Reputation: 1250

Try this:

library(dplyr)
library(reshape)

data %>% cbind(.,colsplit(data$options, "after|before", c("new1", "new2"))) %>%
      select(-options)

Upvotes: 1

Related Questions