Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

So as a beginner, I'm trying to do simple text-mining (NLP) using R language.

I preprocessed my data using tm_map function and inspected it and all the punctuations, numbers were removed. I also converted the text document in lower case using tolower() function. It worked great.

But while creating a document matrix, I'm encountering an issue where the error is:

error in tolower(txt): non character argument

What is this error about and how to go ahead with this? Is this something related to UTF8? Any leads would be appreciated.

docs <- tm_map(docs, removePunctuation) 
inspect(docs[1]) 

for(j in seq(docs)) { 
  docs[[j]] <- gsub("
", " ", docs[[j]]) 
} 

docs <- tm_map(docs, removeNumbers) 
docs <- tm_map(docs, content_transformer(tolower)) 
docs <- tm_map(docs, removeWords, stopwords("english")) 
docs <- tm_map(docs, stripWhitespace) 

This all worked just fine and my text document (which is simply an ebook) got converted into lower case, with no white spaces, numbers, etc. just fine and the next step returns the error.

# returns the above error. 
dtm <- DocumentTermMatrix(docs)
question from:https://stackoverflow.com/questions/65895168/error-in-tolowertxt-non-character-argument-in-r-for-textmining

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
882 views
Welcome To Ask or Share your Answers For Others

1 Answer

The problem is not turning your corpus into a DocumentTermMatrix. The problem lies in your for loop. It turns your corpus into a list of characters.

If you want to use gsub like this, you need to use the content_transformer function.

# removes the need of the for loop and keeps everything in a corpus.
docs <- tm_map(docs, content_transformer(function(x) gsub("
", " ", x)))

This removes the need of the loop and keeps everything as it should be. After this line you can run the rest of your code without any issue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...