因此,我使用中的R tidyr,我试图将数据在分离'pub_author'柱(附后)到3个单独的列:'website_title','year',和'author'。我尝试使用separate()函数做separate('pub_author',c('website_title','year', 'author'),'-'),但由于 R'-'单独读取每个,它只返回前三个单词。有谁知道如何将标题和作者的单词分组,以便它们出现在适当的列或任何其他方法中?
使用separate,我们可以通过正则表达式查找。在这种情况下,将匹配-4 位数字之前或-4 位数字之后的 a
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
Run Code Online (Sandbox Code Playgroud)
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))
Run Code Online (Sandbox Code Playgroud)