当你分解成更小的问题时,事情变得非常容易。在这里,我正在创建test
可以在代码中替换为df$your.column
.
test <- c("charge", "charges", "container charges", "store charges", "something else")
首先,您需要定义不同的条件,如下所示:
haschargeandnotcharges <- grepl("charge", test) & !grepl("charges", test)
hascontainerchargesorstorecharges <- grepl("container charge", test)|grepl("store charge", test)
hasnocharge <- grepl("charge", test)
然后你可以应用你的不同规则
result <- ifelse(haschargeandnotcharges, gsub("charge", "charges", test), test)
result <- ifelse(hascontainerchargesorstorecharges, gsub("charges", "charge", result), result)
result <- ifelse(hascontainerchargesorstorecharges, gsub("charges", "charge", result), result)
result <- ifelse(hasnocharge, paste(result, "charges"), result)
rbind(test,result)
[,1] [,2] [,3]
test "charge" "charges" "container charges"
result "charges" "charges charges" "container charge charges"
[,4] [,5]
test "store charges" "something else"
result "store charge charges" "something else charges"
下次尝试请给我们一个可重现的示例,以便我们为您提供帮助。