I have two columns, first one is 'class' (5 categories) and second one is 'Text'. I have managed to load the text column as a vector corpus = Corpus(VectorSource(data$Text))
I ultimately want to reduce the text list in each row to unique terms which correlate to the class.
input=read.csv("input.csv",stringsAsFactors=FALSE)
library(tm)
library(SnowballC)
corpus = Corpus(DataframeSource(input))
corpus = tm_map(corpus, tolower)
corpus = tm_map(corpus, removeWords, c("apple", stopwords("english")))
corpus = tm_map(corpus, stemDocument)
corpus = tm_map(corpus, stripWhitespace)
dtm = DocumentTermMatrix(corpus,control=list(weighting=weightTfIdf, minWordLength=2))
When I view the corpus it seems to be ignoring the first column, the 'class' column. I'm looking for code to find which words are highly correlated with the different class categories i.e correlate with class 1, but not the other classes.
Thank you
you have a typo in:
corpus = Corpus(DataframeSrouce(input))
change it to:
corpus = Corpus(DataframeSource(input))
Related
I have a document out of which I have special characters along with text such as !, #, #, $, % and more. The following code is used to obtain the most frequent terms list. But when it is performed, the special characters are missing in the frequent terms list i.e. if "#StackOverFlow" is the word present 100 times in the document, I get it as "StackOverFlow" without # in the frequent terms list. Here is my code:
review_text <- paste(rome_1$text, collapse=" ")
#The special characters are present within review_text
review_source <- VectorSource(review_text)
corpus <- Corpus(review_source)
corpus <- tm_map(corpus, stripWhitespace)
corpus <- tm_map(corpus, removeWords, stopwords("english"))
dtm <- DocumentTermMatrix(corpus)
dtm2 <- as.matrix(dtm)
frequency <- colSums(dtm2)
frequency <- sort(frequency, decreasing = TRUE)
head(frequency)
Where exactly have I gone wrong here?
As you can see in the DocumentTermMatrix documentation :
This is different for a SimpleCorpus. In this case all options are
processed in a fixed order in one pass to improve performance. It
always uses the Boost Tokenizer (via Rcpp) and takes no custom
functions as option arguments.
It seems that SimpleCorpus objects (created by Corpus function) use a pre-defined Boost tokenizer which automatically splits words removing punctuations (including #).
You could use VCorpus instead, and removes the punctuations characters you want e.g. :
library(tm)
review_text <-
"I love #StackOverflow. #Stackoverflow is great, but Stackoverflow exceptions are not!"
review_source <- VectorSource(review_text)
corpus <- VCorpus(review_source) # N.B. use VCorpus here !!
corpus <- tm_map(corpus, stripWhitespace)
corpus <- tm_map(corpus, removeWords, stopwords("english"))
patternRemover <- content_transformer(function(x,patternToRemove) gsub(patternToRemove,'',x))
corpus <- tm_map(corpus, patternRemover, '\\!|\\.|\\,|\\;|\\?') # remove only !.,;?
dtm <- DocumentTermMatrix(corpus,control=list(tokenize='words'))
dtm2 <- as.matrix(dtm)
frequency <- colSums(dtm2)
frequency <- sort(frequency, decreasing = TRUE)
Result :
> frequency
#stackoverflow exceptions great love stackoverflow
2 1 1 1 1
Using R{tm} package, i create a corpus, per usual:
mycorpus <- Corpus(DirSource(folder,pattern="txt"))
Please note I am not using an encoding variable. The summary (mycorpus) shows document names listed. However after a series of tm_map transforms:
(content_transformer(tolower),content_transformer(removeWords), stopwords("SMART"),stripWhitespace)
ending with mycorpus<- tm_map(mycorpus, PlainTextDocument) and mydtm <- DocumentTermMatrix(mycorpus, control = list(...))
I get an error with inspect(mydtm[1:10, intersect(colnames(dtm), 'toyota')]) to get my variable of choice:
Terms
Docs toyota
character(0) 0
character(0) 0
character(0) 0
character(0) 0
character(0) 1
character(0) 0
character(0) 0
character(0) 0
character(0) 1
character(0) 0
The file names (doc ids) have disappeared. Any idea what could be causing this error? more importantly, how do i reinstate the document names? Many thanks.
Code below will work for single file. You likely could use something like list.files to read all files in the directory.
First, I would wrap the cleaning functions in a custom function. Note the order matters and you have to use content_transformer if the function is not from tm.
clean.corpus<-function(corpus){
corpus <- tm_map(corpus, removePunctuation)
corpus <- tm_map(corpus, stripWhitespace)
corpus <- tm_map(corpus, removeNumbers)
corpus <- tm_map(corpus, content_transformer(tolower))
corpus <- tm_map(corpus, removeWords, custom.stopwords)
return(corpus)
}
Then concatenate English words with custom words. This is passed as the last part of the custom function above.
custom.stopwords <- c(stopwords('english'), 'lol', 'smh')
doc<-read.csv('coffee.csv', header=TRUE)
The CSV is a data frame with a column of tweets in a text document and another column with an ID for each tweet. The file from my workshop with this file is here.
The csv file is now in memory so next step is to read it in tabular fashion with a specific mapping when making a corpus. Here the content is in a column called text and the unique ID is in a column name "id".
custom.reader <- readTabular(mapping=list(content="text", id="id"))
corpus <- VCorpus(DataframeSource(doc), readerControl=list(reader=custom.reader))
corpus<-clean.corpus(corpus)
The corpus creation uses the readerControl and then once done you can apply the pre-processing steps. Without the reader control the package assigns the 0 character as the name.
The corpus content of document 1 can be accessed here
corpus[[1]][1]
You can review the corpus meta data for the first document with this code
corpus[[1]][2]
So I think you are needing to use readTabular and readerControl in your corpus construction no matter the source.
I was having the same problem and I realized that it was due to tolower. tolower, unlike removeNumbers, removePunctuation, removeWords, stemDocument, stripWhitespace are not tranformations defined in the tm package. To get a list of transformations defined in the tm package that can be directly applied to a corpus, type:
getTransformations()
[1] “removeNumbers” “removePunctuation” “removeWords” “stemDocument” “stripWhitespace”
Thus, in order to use tolower it first must make a transformation for tolower for it to handle corpus objects properly.
docs <- tm_map(docs,content_transformer(tolower))
The above line of code should stop the files from being renamed to character(0)
The same trick can be applied to any R function to work with corpuses. For example for gsub, the following syntax applies:
docs <- tm_map(docs, content_transformer(gsub), pattern = “internt”, replacement = “internet”)
I am new to R. I have a CSV file that includes 15000 rows of text, each row belongs to one person. I want to do Latent Dirichlet Allocation on it. But, first I need to create a term document matrix. However, I don't know how to make R to treat each row as a document. Here is what I've done, but it doesn't look correct:
text <- read.csv("text.csv", stringsAsFactors = FALSE)
corpus Corpus(VectorSource(text))
corpus <- tm_map(corpus, content_transformer(removePunctuation))
corpus <- tm_map(corpus, removeWords, stopwords("english"))
corpus <- tm_map(corpus, removeNumbers)
corpus <- tm_map(corpus, stemDocument)
corpus <- tm_map(corpus, stripWhitespace)
dtm <- DocumentTermMatrix(corpus)
the current dtm doesn't look like having all the terms in all the documents in columns. I feel like they're only words in each document.
I really appreciate your help
I am completing a project in which I using R to text mine and compare this to other variables. I am relatively new to programming so any help would be appreciated.
I have a csv file with over 100 variables and one of the variables is a comment section filled with text. I have managed to clean the file and treat the the column as a corpus and remove english stop words, remove punctuation etc. Here is the code for this, with the first quarter data file read in:
com <- read.csv("dataQ1", stringsAsFactors=TRUE)
Then remove NA and blank spaces
comna <- com[!(is.na(com$Comment) | com$Comment==""), ]
Create a corpus to clean further, this done by using the tm package and helps remove punctation, numbers and english stopwords (words like 'and' or 'the') amongst other things as shown in this code.
corpus <- Corpus(VectorSource(comna$Comment))
corpus <- tm_map(corpus, tolower, mc.cores=1)
corpus <- tm_map(corpus, mc.cores=1, removePunctuation)
corpus <- tm_map(corpus, removeNumbers, mc.cores=1)
corpus <- tm_map(corpus, removeWords, stopwords("english"), mc.cores=1)
corpus <- tm_map(corpus, PlainTextDocument)
Now I would like to explore the data by comparing this to another variable in csv file like 'Overall Satisfaction.' So if I extract certain words like 'abroad,' and 'charges,' and then plot this in ggplot as follows by using the following code:
wordExtr <- subset(comna, grepl("abroad|charges", Comment))
os <- ggplot(wordExtr, aes(factor(wordExtr$Overall.Satisfaction)))
c + geom_bar()
Giving the following ggplot:
However this plot is comparing the variable on when blank spaces and NAs have been removed I would like to compare the variable to corpus object I created which removed punctuation, capital letters, stopwords etc. So my two questions are as follows.
1. How do I select the column that I have created a corpus object and compare this to the 'overall satifaction,' varaible? i.e not the column that has just the NAs and blank spaces removed as shown above.
2. As stated I have read in quarter 1, can I read in quarter 2 and plot on the same ggplot the results of quater 2? So for example I would like a graph that measures the 'overall satisfaction,' over 4 quarters.
Any help in how I can code this would really help, and if there is anything that is unclear, please ask with a follow up question. Thanks
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
library functions
library(tm)
library(e1071)
library(plyr)
Inserting the journal names to be categorized
sample = c(
"An Inductive Inference Machine",
"Computing Machinery and Intelligence",
"On the translation of languages from left to right",
"First Draft of a Report on the EDVAC",
"The Rendering Equation")
corpus <- Corpus(VectorSource(sample))
corpus <- tm_map(corpus, removeNumbers)
corpus <- tm_map(corpus, removePunctuation)
corpus <- tm_map(corpus, tolower)
corpus <- tm_map(corpus, removeWords, stopwords("english"))
corpus <- tm_map(corpus, stemDocument,language="english")
corpus <- tm_map(corpus, stripWhitespace)
dtm <- DocumentTermMatrix(corpus)
term document matrix as training set
inspect(dtm)
Category=c("Machine learning","Artificial intelligence","Compilers","Computer architecture","Computer graphics")
declaration of the categories
my.data=data.frame(as.matrix(dtm),Category)
my.data
sample = c(
"gprof: A Call Graph Execution Profiler",
"Architecture of the IBM System/360",
"A Case for Redundant Arrays of Inexpensive Disks (RAID)",
"Determining Optical Flow",
"A relational model for large shared data banks",
"some complementarity problems of z and lyoponov like transformations on edclidean jordan algebra")
corpus <- Corpus(VectorSource(sample))
corpus <- tm_map(corpus, removeNumbers)
corpus <- tm_map(corpus, removePunctuation)
corpus <- tm_map(corpus, tolower)
corpus <- tm_map(corpus, removeWords, stopwords("english"))
corpus <- tm_map(corpus, stemDocument,language="english")
corpus <- tm_map(corpus, stripWhitespace)
dtm1 <- DocumentTermMatrix(corpus)
term document matrix as testing set
inspect(dtm1)
Well, your sample data has absolutely no overlapping terms, so there's not really much you can do there. The tm library doesn't assign meaning to words, it just measures their correlation. So you need to supply enough overlapping data so that is has a chance of matching up new input to an existing corpus.
Once you actually have real data, you have many options on how you want to build a model. You can use a kNN classifier like that in the class package, or a decision tree like that in the rpart package, or a neural network like that in the nnet package. There are examples of each of those in this presentation. But it's up to you to decide what's right for your data. That part is not a programming related question.