[英]Adding a Column in R (character) based off of what is contained in another column (character) within the same data
我正在尝试根据同一数据中不同列中包含的内容向我的数据添加一列。 因此,仅举一个我正在寻找的示例:
A 栏:“Apple Bees 在正确的区域”“我们喜欢这里的 Apple Bees”“华夫饼屋:去的地方!5 星”“没有比华夫饼屋更好的了!”
注意:A 列的值为 chr
我希望 F 列显示:“Apple Bees”“Apple Bees”“Waffle House”“Waffle House”
我尝试了 mutate, contains, select, %in%,但我一直收到一堆错误。 我假设我应该在 dplyr package 中使用其中的一个或多个,但我没有得到我想要的结果。 任何建议,将不胜感激。 谢谢!
尝试这个:
library(dplyr)
library(stringr)
restaurants <- c("Apple Bees",
"Waffle House") %>%
paste(collapse = "|")
my_df <- data.frame(
matrix(
c(
"Apple Bees in the right area",
"We love Apple Bees here",
"Waffle House: the place to go! 5 stars",
"Nothing better than Waffle House!"
),
nrow = 4,
ncol = 1,
byrow = TRUE,
dimnames = list(NULL,
c("phrase"))
),
stringsAsFactors = FALSE
)
my_df_new <- my_df %>%
mutate(
restaurant_in_phrase = str_extract(phrase, restaurants)
)
如果您要处理大量字符串和短语,我强烈建议您熟悉正则表达式或正则表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.