2016-03-20 11 views
0

の数の割合として報告しているだろう:与えられたテキストにその頻度をカウントし、特定の文字列を検索し、Rで関数を記述しようとする言葉

1)各観測の文字列変数に目を通す

2)ユーザが定義した特定の文字列を特定してカウントする。

3)結果が、各観測に含まれる単語の総数の割合として報告する。この機能

df <- data.frame(essay1=c("OMG. american sign language. knee-slides in leather pants", "my face looks totally different every time. lol."), 
      essay2=c("cheez-its and dried cranberries. sparkling apple juice is pretty\ndamned coooooool too.<br />\nas for music, movies and books: the great american authors, mostly\nfrom the canon, fitzgerald, vonnegut, hemmingway, hawthorne, etc.\nthen of course the europeans, dostoyevski, joyce, the romantics,\netc. also, one of the best books i have read is all quiet on the\nwestern front. OMG. I really love that. lol", "at i should have for dinner\nand when; some random math puzzle, which I loooooove; what it means to be alive; if\nthe meaning of life exists in the first place; how the [email protected]#$ can the\npolitical mess be fixed; how the %^&amp;* can the education system\nbe fixed; my current game design project; my current writing Lol"), 
      essay3=c("Lol. I enjoy life and then no so sure what else to say", "how about no?")) 

私は得ることができたfurtherestされています:これは、与えられた値は「エッセイ」の中にあるかどうかを検出するために、ユーザーを可能

find.query <- function(char.vector, query){ 
    which.has.query <- grep(query, char.vector, ignore.case = TRUE) 
    length(which.has.query) != 0 
} 
profile.has.query <- function(data.frame, query){ 
    query <- tolower(query) 
    has.query <- apply(data.frame, 1, find.query, query=query) 
    return(has.query) 
} 

ここ

は、サンプルデータセットの与えられたものの、上で概説した3つの目標のためには十分ではありません。この機能が理想的に行うことは、特定された単語の数を数え、その総数を全体のエッセイ(各ユーザーの行の合計)で除算することです。

これにアプローチする方法についてのアドバイスはありますか?この記事のようにstringiパッケージを使用して

+0

ご質問ご入力data.frameを確認してください、あなたはおそらく」didnのそれはエラーを与えるので、いくつかの引用符をエスケープする... – digEmAll

+0

はい、私の悪い!今働いているはずです。 – Cauchy

答えて

0

How do I count the number of words in a text (string) in R?

library(stringi) 

words.identified.over.total.words <- function(dataframe, query){ 
    # make the query all lower-case 
    query <- tolower(query) 

    # count the total number of words 
    total.words <- apply(dataframe, 2, stri_count, regex = "\\S+") 

    # count the number of words matching query 
    number.query <- apply(dataframe, 2, stri_count, regex = query) 

    # divide the number of words identified by total words for each column 
    final.result <- colSums(number.query)/colSums(total.words) 

    return(final.result) 
} 

(あなたの問題のDFは、各列の列の各エッセイを持っているので、機能和しかし、テキストインチあなたは、行の合計をしたいと言う。入力されたデータフレームは、行ごとに1つのエッセイを持ってのものだった場合、あなたはそれを反映するために機能を変更することができます。)

+0

これは素晴らしいです!そしてそれはかなりうまくいく。 行に関数を変更するために、明確にするために、我々は、であることが行3及び4を変更します 'total.words < - 適用(データフレーム、1、stri_count、正規表現= "\\ S +") number.query 次に、5行目の行を次のように変更します。 'final.result < - rowsum(number.query)/ rowsum(total.words)' - apply(dataframe、1、stri_count、regex = query) – Cauchy

関連する問題