Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: removal of regex from Quanteda DFM, Sparse Document-Feature Matrix, object?

Quanteda package provides the sparse document-feature matrix DFM and its methods contain removeFeatures. I have tried dfm(x, removeFeatures="\\b[a-z]{1-3}\\b") to remove too short words as well as dfm(x, keptFeatures="\\b[a-z]{4-99}\\b") to preserve sufficiently long words but not working, basically doing the same thing i.e. removing too short words.

How can I remove a regex match from a Quanteda DFM object?

Example.

myMatrix <-dfm(myData, ignoredFeatures = stopwords("english"), 
           stem = TRUE, toLower = TRUE, removeNumbers = TRUE, 
           removePunct = TRUE, removeSeparators = TRUE, language = "english")
#
#How to use keptFeatures/removeFeatures here?


#Instead of RemoveFeatures/keptFeatures methods, I tried it like this but not working
x<-unique(gsub("\\b[a-zA-Z0-9]{1,3}\\b", "", colnames(myMatrix))); 
x<-x[x!=""]; 
mmyMatrix<-myMatrix; 
colnames(mmyMatrix) <- x

Sample DFM

myData <- c("a aothu oat hoah huh huh huhhh h h h n", "hello h a b c d abc abcde", "hello hallo hei hej", "Hello my name is hhh.")
myMatrix <- dfm(myData)
like image 948
hhh Avatar asked Oct 18 '22 19:10

hhh


1 Answers

It's dfm_select, in >= v0.9.9:

myMatrix
## Document-feature matrix of: 4 documents, 22 features (70.5% sparse).

dfm_select(myMatrix, "\\b[a-zA-Z0-9]{1,3}\\b", selection = "keep", valuetype = "regex")
## kept 14 features, from 1 supplied (regex) feature types
## Document-feature matrix of: 4 documents, 14 features (71.4% sparse).
## 4 x 14 sparse Matrix of class "dfmSparse"
##        features
## docs    a oat huh h n b c d abc hei hej my is hhh
##   text1 1   1   2 3 1 0 0 0   0   0   0  0  0   0
##   text2 1   0   0 1 0 1 1 1   1   0   0  0  0   0
##   text3 0   0   0 0 0 0 0 0   0   1   1  0  0   0
##   text4 0   0   0 0 0 0 0 0   0   0   0  1  1   1
like image 112
Ken Benoit Avatar answered Oct 20 '22 09:10

Ken Benoit