Partial animal string matching in R

霸气de小男生 提交于 2019-11-28 18:51:30

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".

You might want to add ignore.case = TRUE to the grep.

output:

#                 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

An elegant-ish way of doing this (I say elegant-ish because, while it's the most elegant way I know of, it's not great) is something like:

#Define the regexes at the beginning of the code
regexes <- list(c("(cat|lion|tiger|panther)","feline"),
                c("(bird|eagle|sparrow)","avian"),
                c("(dog|yorkie|bulldog)","canine"))

....


#Create a vector, the same length as the df
output_vector <- character(nrow(d))

#For each regex..
for(i in seq_along(regexes)){

    #Grep through d$name, and when you find matches, insert the relevant 'tag' into
    #The output vector
    output_vector[grepl(x = d$name, pattern = regexes[[i]][1])] <- regexes[[i]][2]

} 

#Insert that now-filled output vector into the dataframe
d$species <- output_vector

The advantage of this method are several-fold

  1. You only have to modify the data frame once in the entire process, which increases the speed of the loop (data frames do not have modification-in-place; to modify a data frame 3 times, you're essentially relabelling and recreating it 3 times).
  2. By specifying the length of the vector in advance, since we know what it's going to be, you increase speed even more by ensuring that the output vector never needs more memory allotted after it is created.
  3. Because it's a loop, rather than repeated, manual calls, the addition of more rows and categories to the 'regexes' object will not require further modification of the code. It'll run just as it does now.

The only disadvantage - and this applies to, I think, most solutions you're likely to get, is that if something matches multiple patterns, the last pattern in the list it matches will be its 'species' tag.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!