简体   繁体   中英

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")

Try this:

library(dplyr)
library(reshape)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM