【问题标题】:Parsing Columns and Identifying Fields in R在 R 中解析列和识别字段
【发布时间】:2017-06-30 22:35:46
【问题描述】:

这是我的 df 示例:

data
276 '83 Rally '83 (1983) (V)\t\t\t\t1983
277 '87: A Love Story (2007)\t\t\t\t2007                                                                                                   
278 '88 Dodge Aries (2002)\t\t\t\t\t2002
279 '9': Acting Out (2009) (V)\t\t\t\t2009

我想创建一个仅显示标题和年份的数据框。有人对如何解析这个有任何建议吗?我想我可能需要拆分\t\t\t\t 上的列

     Title                Year 
276 '83 Rally '83     (1983) 
277 '87: A Love Story (2007)                                                                                             
278 '88 Dodge Aries   (2002)
279 '9': Acting Out   (2009) 

这是输出

c("# (2014)\t\t\t\t\t\t2014", "#1 (2005)\t\t\t\t\t\t2005", "#1 (2009)\t\t\t\t\t\t2009", 
"#1 (2010)\t\t\t\t\t\t2010", "#1 (2010/I) (V)\t\t\t\t\t\t2010", 
"#1 (2010/II) (V)\t\t\t\t\t2010")

【问题讨论】:

  • 您目前实际上有多少列? 1? A dput would be helpful.
  • 实际上,您给出的示例并没有使您的 data.frame 的结构明显。您能否以显示结构的方式提供您的数据?请使用dput(df) 并将结果粘贴到您的问题中。如果你的数据很长,可以使用dput(head(df))
  • @alistaire @G5W 目前我只有一列名为data。它包含电影信息字符串(标题、发布日期)我不熟悉 dput,但我运行了这个:dput(head(df)),我会将输出放在问题中。

标签: r string parsing


【解决方案1】:

使用gsub():

df$Title <- gsub("(.*?) \\(.*", "\\1", df$data)
df$Year  <- gsub(".*\\((\\d{4})\\).*", "\\1", df$data)

> df[c("Title", "Year")]
                  Title Year
1     276 '83 Rally '83 1983
2 277 '87: A Love Story 2007
3   278 '88 Dodge Aries 2002
4   279 '9': Acting Out 2009

注意:如果data实际上是一个独立的向量,那么直接使用它就可以了,例如

Title <- gsub("(.*?) \\(.*", "\\1", data)

下面是用于提取年份的正则表达式的解释:

.*        match everything
\\(       up until the first parenthesis
(\\d{4})  then capture a four digit year
\\)       followed by a closing parenthesis
.*        consume the remainder of the string

\\1 用作替换 gsub() 的数量使用在比赛期间捕获的四位数年份。

【讨论】:

  • 谢谢。当我尝试你的代码时,我得到了这个错误:Error in df$data : $ operator is invalid for atomic vectors
  • 听起来data 不是一个数据框,它只是一个字符串向量。在这种情况下,只需在我上面给出的代码 sn-p 中将 df$data 替换为 data
  • 谢谢,我修复了我的数据,现在它在 df 中。你介意解释你的正则表达式 - 特别是'df$year'中使用的正则表达式
猜你喜欢
  • 2011-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-15
  • 2019-09-10
  • 1970-01-01
  • 2021-12-24
相关资源
最近更新 更多