簡體   English   中英

通過解析R中的字符向量構建數據幀

[英]Building a dataframe by parsing character vectors in R

我是R的新手,正在努力從博物館的藏品中構建數據集。

抓取他們的網站后,我得到了一個字符向量列表(假設名稱為“特征”),其中每個元素如下所示:

[[4729]]
[1] " Date://2002 Medium://Pencil on paper Dimensions://22 1/2 x 30 1/8\" (57.2 x 76.5 cm) Credit Line://The Judith Rothschild Foundation Contemporary Drawings Collection Gift MoMA Number://1563.2005 Copyright://© 2015 Steve DiBenedetto"

從這些向量,我想制作一個數據幀,如下所示:

     year    medium           dimensions    credit line    number
1   2002     Pencil on paper   etc...

但是,我似乎無法設法從字符向量中減去必要的數據,因為我正努力使用正則表達式。 想法是獲取在“ Date://”之后和“ Medium://”之前的內容。 為了使事情變得更復雜,列表中的每個元素並非都具有相同的特征(例如,某些元素僅具有“日期”和“中號”,而其他元素包括“ edition://”,“通過://獲取”)等)。

只需保存每個列表元素中的前4位數字,就可以很容易地編制年份列表:

year <- list()

for(p in 1:length(characteristics)) {
  string <- as.character(characteristics[p])
  year <- c(year, str_extract(string, "\\d\\d\\d\\d"))
  }

這可能甚至不是最快的方法,但效果很好。 但是,我完全堅持從列表中提取其他變量。

也許不錯的舊read.table也可以選擇:

txt <- c("Date://2002 Medium://Pencil on paper Dimensions://22 1/2 x 30 1/8\" (57.2 x 76.5 cm) Credit Line://The Judith Rothschild Foundation Contemporary Drawings Collection Gift MoMA Number://1563.2005 Copyright://© 2015 Steve DiBenedetto",
         "Date://2002 Medium://Pencil on paper Dimensions://22 1/2 x 30 1/8\" (57.2 x 76.5 cm) Credit Line://The Judith Rothschild Foundation Contemporary Drawings Collection Gift MoMA Number://1563.2005 Copyright://© 2015 Steve DiBenedetto")
read.table(text = gsub("( Credit)?\\s?[A-z]+://", "\t", txt), sep = "\t", quote = "", col.names = letters[1:7])[-1]
#      b               c                                 d                                                                           e      f                        g
# 1 2002 Pencil on paper 22 1/2 x 30 1/8" (57.2 x 76.5 cm) The Judith Rothschild Foundation Contemporary Drawings Collection Gift MoMA 1563.2 © 2015 Steve DiBenedetto
# 2 2002 Pencil on paper 22 1/2 x 30 1/8" (57.2 x 76.5 cm) The Judith Rothschild Foundation Contemporary Drawings Collection Gift MoMA 1563.2 © 2015 Steve DiBenedetto

暫無
暫無

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

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