【问题标题】:R Extract patterns in strings vectorised within a dataframeR在数据帧内向量化的字符串中提取模式
【发布时间】:2015-11-26 09:28:41
【问题描述】:

我有一个包含“描述”列的数据框,我需要将其拆分为“产品”和“平面块”列。我已经模拟了一些虚拟数据来说明我的任务。我已经(通过使用 RWeka::NGramTokenizer 的过程)成功生成了“产品”列。

数据看起来像......

my_dataframe = data.frame(description = c("ford fiesta blue fast","red toyota japanese very fast","rolls royce phantom black",
                                      "yellow beach buggie with spare wheel","harrier jump jet vertical take off",
                                      "american jeep with seat belt","suzuki motorbike with built in fridge"),
                      product = c("fiesta","red toyota","rolls royce","beach buggie","jump jet","american jeep","motorbike"))

尽管我在下一步中被困住了,但我会非常感谢任何帮助。我正在尝试从“描述”中的相对位置中提取“产品”中的字符串。为免生疑问,我的目标 my_dataframe$facetblock 列看起来像这样......

my_dataframe$facetblock = c("ford blue fast", "japanese very fast", "phantom black", "yellow with spare wheel", "harrier vertical take off", "with seat belt", "suzuki with built in fridge")

我从 base、stringr、stringi 和 qdap 包(grep、str_extract、stri_extract、mgsub)尝试了许多不同的开箱即用方法,但没有成功。我也尝试过编写自己的 sapply 函数,但还没有运气

my_dataframe$facetblock = sapply(mydata, function(x) str_extract(mydata$description[x], mydata$product[x]))

my_dataframe$facetblock = sapply(mydata$description, function(x) grep(mydata$product[x], mydata$description[x], value = TRUE, invert = TRUE))

有没有人可以和我分享一下解决方案?提前谢谢。

【问题讨论】:

  • 试试library(stringi) ; with(my_dataframe, stri_replace_first_fixed(description, product, "")
  • sapply(1:7,function(x){sub(paste0(data$product[x],' '),'',data$description[x])})

标签: r string replace


【解决方案1】:

您可以使用stri::stri_replace_first_fixed 对其进行矢量化(您也可以更改为last/all

library(stringi) 
with(my_dataframe, stri_replace_first_fixed(description, product, ""))
# [1] "ford  blue fast"              " japanese very fast"          " phantom black"               "yellow  with spare wheel"    
# [5] "harrier  vertical take off"   " with seat belt"              "suzuki  with built in fridge"

如果您不喜欢前导空格,可以将其包装到新的 trimwsstringi::stri_trim(根据 @akruns 评论)函数中。

【讨论】:

  • 如果您使用的是stringi,则可以选择stri_trim (+1)
  • 感谢@David 和 etienne。大卫的回答成功了。非常感谢!
猜你喜欢
  • 2018-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-14
相关资源
最近更新 更多