【发布时间】: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])})