2016-11-07 86 views
1

合作次数矩阵我想计算R.一句话合作次数矩阵我有句以下数据帧 -计算字r中

dat <- as.data.frame("The boy is tall.", header = F, stringsAsFactors = F) 
dat[2,1] <- c("The girl is short.") 
dat[3,1] <- c("The tall boy and the short girl are friends.") 

这给了我

The boy is tall. 
The girl is short. 
The tall boy and the short girl are friends. 

我想要做的是首先让所有三句话所有的独特的单词列表,即

The 
boy 
is 
tall 
girl 
short 
and 
are 
friends 

然后,我会想创建它计算了多少次话共同出现在一个句子中总共这将是这个样子

 The boy is tall girl short and are friends 
The  0  2  2  2  2  2  1  1 1 
boy  2  0  1  2  1  1  1  1 1 
is  2  1  0  2  1  1  0  0 0 
tall 2  2  1  0  1  1  1  1 1 
etc. 

所有的词,词共次数矩阵,其中一个字不能合作 - 与自身发生一致。请注意,在句子3中,如果“the”这个词出现两次,解决方案应该只计算一次该“the”的共同发生次数。

有没有人有一个想法,我可以做到这一点。我正在处理大约3000个句子的数据框。

+1

你尝试过什么,为什么没有工作?你需要显示一些努力,在这里:-) – agenis

+0

看看[tm包](https://cran.r-project.org/web/packages/tm/index.html)。 – zx8754

+0

使用base-R,尝试用'strsplit'和空格分隔每个句子,并用'gsub'删除点,逗号等。对于唯一的单词列表,你可以使用'unique'命令。 –

回答

4
library(tm) 
library(dplyr) 
dat  <- as.data.frame("The boy is tall.", header = F, stringsAsFactors = F) 
dat[2,1] <- c("The girl is short.") 
dat[3,1] <- c("The tall boy and the short girl are friends.") 

ds <- Corpus(DataframeSource(dat)) 
dtm <- DocumentTermMatrix(ds, control=list(wordLengths=c(1,Inf))) 

X   <- inspect(dtm) 
out  <- crossprod(X) # Same as: t(X) %*% X 
diag(out) <- 0    # rm own-word occurences 
out 
 Terms 
Terms boy friend girl short tall the 
    boy  0  1 1  1 2 2 
    friend 1  0 1  1 1 1 
    girl  1  1 0  2 1 2 
    short 1  1 2  0 1 2 
    tall  2  1 1  1 0 2 
    the  2  1 2  2 2 0 

您也可能要删除像停止词 “的”,即

ds <- tm_map(ds, stripWhitespace) 
ds <- tm_map(ds, removePunctuation) 
ds <- tm_map(ds, stemDocument) 
ds <- tm_map(ds, removeWords, c("the", stopwords("english"))) 
ds <- tm_map(ds, removeWords, c("the", stopwords("spanish")))