2013-04-22 42 views
1

我已经尝试了一些不同的程序包,以便构建一个R程序,它将输入文本文件并生成该文件中的单词列表。每个单词应该有一个向量,包含该单词在该文件中存在的所有位置。 作为一个例子,如果文本文件具有字符串:打印发生/字的位置

"this is a nice text with nice characters" 

输出应该是这样的:

$this 
[1] 1 

$is  
[1] 2 

$a   
[1] 3 

$nice  
[1] 4 7 

$text 
[1] 5 

$with 
[1] 6 

$characters 
[1] 8 

我碰到一个有用的帖子,http://r.789695.n4.nabble.com/Memory-usage-in-R-grows-considerably-while-calculating-word-frequencies-td4644053.html来了,但它不包括位置的每个字。 我发现了一个名为“str_locate”的类似函数,但是我想要计算“单词”而不是“字符”。

的,是在使用什么包/技术,将是任何指导,非常感谢

回答

7

你可以用基础R做到这一点(这奇怪的精确产生你所建议的输出):

# data 
x <- "this is a nice text with nice characters" 
# split on whitespace 
words <- strsplit(x, split = ' ')[[1]] 
# find positions of every word 
sapply(unique(words), function(x) which(x == words)) 

### result ### 
$this 
[1] 1 

$is 
[1] 2 

$a 
[1] 3 

$nice 
[1] 4 7 

$text 
[1] 5 

$with 
[1] 6 

$characters 
[1] 8 
+0

非常感谢你许多!有用。我需要检查“sapply”文档,然后获取更多信息(不知道) – ardarel 2013-04-22 17:57:50