How to use tidyr in R to separate a string column into multiple other columns

Viewed 93

So I am using tidyr in R and I am trying to separate the data in the 'pub_author' column (attached below) into 3 individual columns: 'website_title', 'year', and 'author'. I tried using the separate() function doing separate('pub_author',c('website_title','year', 'author'),'-'), but since R reads each '-' individually it only returns the first three words. Does anyone know how to group the words for title and author so that they will appear in the appropriate column or any other method?

pub author column

1 Answers

With separate, we can pass regex lookarounds. In this case, it would be to match - that precedes a 4 digit or a - that succeeds a 4 digit

library(tidyr)
separate(df1, pub_author, into = c('website_title','year', 'author'), 
     "-(?=\\d{4})|(?<=\\d{4})-")
#        website_title year        author
#1       nfl-draft-geek 2018 justin-miller
#2                  cbs 2019   pete-prisco
#3            sb-nation 2020     dan-kadar
#4    football-fan-spot 2019 steven-lourie
#5             fanspeak 2018       william
#6 acme-packing-company 2020  shawn-wagner

data

df1 <- structure(list(pub_author = c("nfl-draft-geek-2018-justin-miller", 
"cbs-2019-pete-prisco", "sb-nation-2020-dan-kadar", 
  "football-fan-spot-2019-steven-lourie", 
"fanspeak-2018-william", "acme-packing-company-2020-shawn-wagner"
)), class = "data.frame", row.names = c(NA, -6L))
Related