簡體   English   中英

如何在 R 中使用 tidyr 將一個字符串列分成多個其他列

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

所以我在 R 中使用 tidyr,我試圖將'pub_author'列(附在下面)中的數據分成 3 個單獨的列: 'website_title''year''author' 我嘗試使用單獨的() function 做separate('pub_author',c('website_title','year', 'author'),'-') ,但是由於 R 單獨讀取每個'-'它只返回前三個字。 有誰知道如何對標題和作者的單詞進行分組,以便它們出現在適當的列或任何其他方法中?

發布作者專欄

使用separate的,我們可以通過正則表達式環視。 在這種情況下,它將匹配-在 4 位之前或-在 4 位之后

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

數據

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM