Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert vector of characters to corpus input for the DocumentTermMatrix function from tm package in R?

Tags:

r

tm

I am new to tm package. I'd like to use DocumentTermMatrix function to create DT- Matrix for further text-mining analysis but I am able to create propoer input for that function.

I have my data input so far in a format of a character vector like this and tried to use as.VCorpus function but it look's like it does not work. Code below:

> x <- as.VCorpus(sekcja_link$slowa_kluczowe_2)
Error in UseMethod("as.VCorpus") : 
  no applicable method for 'as.VCorpus' applied to an object of class "character"
> head(sekcja_link$slowa_kluczowe_2)
[1] "mandat policja zima kara"                                                                                 
[2] "sprzedaż samochodów w 2014 rok wzrost sprzedaży utrata prawa jazda wyprzedzać trzeci poduszka powietrzny"
[3] "kobieta 40stce powinien ruszać walczyć życie ewa minge kasia czaplejewicz fitness"                       
[4] "e booki książka elektroniczny papierowy czytnik amazon kindle książki rynek booków handel i usługi"       
[5] "gra monopoly warszawa miasto plebiscyt samorząd i administracja"                                          
[6] "rachunek za ogrzewać niższe koszt ogrzewać ciepło wiek dom mieszkać nieruchomości"                     
> 
like image 441
Marcin Kosiński Avatar asked Mar 23 '15 12:03

Marcin Kosiński


1 Answers

If you got a character vector, you can use VectorSource like this:

txt <- c("Hello to you.", "Blah me, too.")
library(tm)
corp <- Corpus(VectorSource(txt))
dtm <- DocumentTermMatrix(corp)
# inspect(dtm)
# <<DocumentTermMatrix (documents: 2, terms: 5)>>
#   Non-/sparse entries: 5/5
# Sparsity           : 50%
# Maximal term length: 5
# Weighting          : term frequency (tf)
# 
# Terms
# Docs blah hello me, too. you.
# 1    0     1   0    0    1
# 2    1     0   1    1    0
like image 69
lukeA Avatar answered Oct 15 '22 14:10

lukeA