2017-03-26 15 views
0

私はラジオフォーマットを試して分類するために使用している機能を持っていますが、正しく機能していません。今%%で文字列が正しく一致していませんか?

findFormat <- function(format) { 
    currentFormat <- c(strsplit(tolower(format), " ")) 
    if ("christian" %in% currentFormat || "gospel" %in% currentFormat || "religious" %in% currentFormat || "religion" %in% currentFormat) { 
    return("Religious") 
    } 
    if ("pop" %in% currentFormat || "contemporary" %in% currentFormat || "mainstream" %in% currentFormat || "top" %in% currentFormat || "hot" %in% currentFormat || "hit" %in% currentFormat) { 
    return("Pop or Contemporary") 
    } 
    if ("rock" %in% currentFormat || "alternative" %in% currentFormat || "indie" %in% currentFormat) { 
    return("Rock, Alternative, or Indie") 
    } 
    if ("country" %in% currentFormat || "southern" %in% currentFormat) { 
    return("Country") 
    } 
    if ("urban" %in% currentFormat || "hip" %in% currentFormat || "rap" %in% currentFormat || "hip-hop" %in% currentFormat) { 
    return("Hip-hop") 
    } 
    if ("jazz" %in% currentFormat || "blues" %in% currentFormat) { 
    return("Jazz or Blues") 
    } 
    if ("latin" %in% currentFormat || "mexican" %in% currentFormat || "international" %in% currentFormat) { 
    return("International") 
    } 
    if ("oldies" %in% currentFormat) { 
    return("Oldies") 
    } 
    if ("news/talk" %in% currentFormat || "news" %in% currentFormat || "talk" %in% currentFormat || "public" %in% currentFormat) { 
    return("News and Talk") 
    } 
    # Default 
    return("Other") 
} 

予想通り、私はfindFormat("rap")を実行する場合には、[1] "Hip-hop"戻りますが、私はfindFormat("rap and rhythm")を実行した場合、私は[1] Otherを取得します。 currentFormatは文字列のベクトルにする必要があり、"rap" %in% c("rap", "and", "rhythm")[1] TRUEを返します。理由はわかりません。どんな助けもありがとう!

+0

は 'debugonce(findFormatを)'実行し、調査してみてください。 – MichaelChirico

+0

もう一つのヒントは、関数の最初の行に問題があることです。 –

+0

@MichaelChiricoこれは助けてくれました - ありがとう!私は、%cの "rap"%(strsplit(tolower( "Rap and Hip-Hop")、)) 'が' [1] FALSE'を返すことを発見しました。 –

答えて

0

私はあなたがより良いかもしれないので、同様に、ルックアップテーブルを使って、この問題を解決することによって提供することと思います。

findFormat = function(fmt) { 
    matchDT = 
    data.table(keyword = c('christian', 'gospel', 'religious', 'religion', 
          'pop', 'contemporary', 'mainstream', 'top', 
          'hot', 'hit', 'rock', 'alternative',' indie', 
          'country', 'southern', 'urban', 'hip', 
          'hop', 'rap', 'jazz', 'blues', 'latin', 
          'mexican', 'international', 'oldies', 
          'news', 'talk'), 
       format = c(rep('Religious', 4L), 
          rep('Pop or Contemporary', 6L), 
          rep('Rock, Alternative, or Indie', 3L), 
          rep('Country', 2L), rep('Hip-Hop', 4L), 
          rep('Jazz or Blues', 2L), 
          rep('International', 3L), 'Oldies', 
          rep('News and Talk', 2L)), 
       key = 'keyword') 
    out = matchDT[strsplit(fmt, '[ [:punct:]]')[[1L]], nomatch = 0L] 
    if (!length(out)) return('Other') else return(out$format) 
} 

findFormat('rap and rhythm') 
# [1] "Hip-Hop" 
関連する問題