根据其他列中的部分匹配替换列中的整个字符串

问题描述 投票:0回答:1

我的问题与这里的问题类似(根据部分匹配替换整个字符串)或这个(根据R中的部分匹配替换整个表达式

我想我有一点点?就是这样的

my tibble? - i wish i could enter a portion of it here, maybe i can...

我尝试使用与链接帖子类似的代码,根据另一列中的部分匹配来更改一列中的文本。它不太有效。

free <- c("journal & radius wear damage","residual magnetism","damaged wheel","gouge in edge","wheel seat")

f2 <- tibble(free)
f2 %>%
  mutate(catag = "Uncategorised") %>%
print(f2)
#classify if contains text 'barrel'
f2$catag[grepl("wheel", f2$free)] <- "Wheel related issue"


print(f2)

它找到了我所有包含“wheel”的匹配项,并将“catag”列更改为“wheel相关问题”,但随后将所有其他列条目设置为“na”

not quite right

有没有办法只更改匹配的,保留不匹配的。我认为这是“变异”的问题,但这是我发现添加具有常量值的列的一种方法。

非常感谢

我尝试寻找解决方案,但总是以相同的帖子告终

r text tibble grepl mutate
1个回答
0
投票

您可以使用

ifelse
有条件地更改值。

transform(f2, catag = ifelse(grepl("wheel", free), "Wheel related issue", "Uncategorised"))

                       free               catag
1 journal & radius wear damage       Uncategorised
2           residual magnetism       Uncategorised
3                damaged wheel Wheel related issue
4                gouge in edge       Uncategorised
5                   wheel seat Wheel related issue
© www.soinside.com 2019 - 2024. All rights reserved.