更新时间:2022-06-13 00:03:30
也许有比这更优雅的解决方案,但是您可以将grep
与|
结合使用以指定其他匹配项.
There may be a more elegant solution than this, but you could use grep
with |
to specify alternative matches.
d[grep("cat|lion|tiger|panther", d$name), "species"] <- "feline"
d[grep("bird|eagle|sparrow", d$name), "species"] <- "avian"
d[grep("dog|yorkie", d$name), "species"] <- "canine"
我假设您的意思是禽鸟",而省略了牛头犬",因为它包含狗".
I've assumed you meant "avian", and left out "bulldog" since it contains "dog".
您可能想将ignore.case = TRUE
添加到grep.
You might want to add ignore.case = TRUE
to the grep.
输出:
# name label species
#1 brown cat 1 feline
#2 blue cat 2 feline
#3 big lion 3 feline
#4 tall tiger 4 feline
#5 black panther 5 feline
#6 short cat 6 feline
#7 red bird 7 avian
#8 short bird stuffed 8 avian
#9 big eagle 9 avian
#10 bad sparrow 10 avian
#11 dog fish 11 canine
#12 head dog 12 canine
#13 brown yorkie 13 canine
#14 lab short bulldog 14 canine