从字符串中提取年份并附加到数据框

时间:2018-01-05 21:32:18

标签: r

我有一个葡萄酒数据集,其中包含一个名为“title”的列,其中包含葡萄酒的标题,包括其年份。参考样本:

  • 拉2013年霞多丽(帕索罗布尔斯)
  • R2 2013 Camp 4 Vineyard Grenache Blanc(Santa Ynez Valley)

我想在字符串中提取年份,即2013年,而不是字符串中其余的数字,例如2,4。

我到了这一部分:

从标题栏中提取年份

wine_tidy2$vintage_year <- as.list(str_extract_all(wine_tidy2$title, "[0-9]+"))

但如何排除其他不属于年度的数字呢?

我想将结果附加到数据框。使用上面的代码,它将结果列表添加到数据框中,如何将数据框添加为另一列整数?

谢谢。

1 个答案:

答案 0 :(得分:3)

您可以通过搜索包含4位数的数字从基地使用sub()regexec()

string <- c('R2 2013 Camp 4 Vineyard Grenache Blanc', 'Santa Ynez Valley 1999', 'dsdd 2015')
sub("^.*([0-9]{4}).*", "\\1", string)
unlist(regmatches(string, regexec("[0-9]{4}", string)))

适用于您的情况:

# create a helper function
yearExtract <- function(string) {
  t <- regmatches(string, regexec("[0-9]{4}", string))
  sapply(t, function(x) {
    if(length(x) > 0){
      return(as.numeric(x))
    } else {
      return(NA)    
    }
  })
}


# create data.frame
title <- c('R2 2013 Camp 4 Vineyard Grenache Blanc', 'Santa Ynez Valley 1999', 'dsdd 15')
distributor <- c('a', 'b', 'd')
wine_tidy2 <- data.frame(title, distributor)

wine_tidy2$vintage_year <- yearExtract(as.character(wine_tidy2$title))
相关问题