Mona Jalal Mona Jalal - 1 year ago 65
R Question

Finding number of occurences of a word in a file using R functions

I am using the following code for finding number of occurences of a word

in a file and I am getting the wrong result. Can you please help me to know what I am missing?

NOTE1: The question is looking for exact occurrence of word "memory"!
NOTE2: What I have realized they are exactly looking for "memory" and even something like "memory," is not accepted! That was the part which has brought up the confusion I guess. I tried it for word "action" and the correct answer is 7! You can try as well.

#names=scan("hamlet.txt", what=character())
names <- scan('', what=character())
Read 28230 items
> length(grep("memory",names))
[1] 9

Here's the file

Answer Source

As pointed by @andrew, my previous answer would give wrong results if a word repeats on the same line. Based on other answers/comments, this one seems ok:

names = scan('', what=character(), quote=NULL )
idxs = grep("memory", names, = TRUE)

# [1] 10
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download