Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting hashtags in several tweets using R

Tags:

r

I desperately want a solution to extracting hashtags from collective tweets in R. For example:

[[1]]
[1] "RddzAlejandra: RT @NiallOfficial: What a day for @johnJoeNevin ! Sooo proud t have been there to see him at #London2012 and here in mgar #MullingarShuffle"

[[2]]
[1] "BPOInsight: RT @atos: Atos completes delivery of key IT systems for London 2012 Olympic Games http://t.co/Modkyo2R #london2012"

[[3]]
[1] "BloombergWest: The #Olympics sets a ratings record for #NBC, with 219M viewers tuning in. http://t.co/scGzIXBp #london2012 #tech"

How can I parse it to extract the list of hashtag words in all the tweets. Previous solutions display only hashtags in the first tweet with these error messages in the code:

> string <-"MonicaSarkar: RT @saultracey: Sun kissed #olmpicrings at #towerbridge #london2012   @ Tower Bridge http://t.co/wgIutHUl"
> 
> [[2]]
Error: unexpected '[[' in "[["
> [1] "ccrews467: RT @BBCNews: England manager Roy Hodgson calls #London2012 a \"wake-up call\": footballers and fans should emulate spirit of #Olympics http://t.co/wLD2VA1K" 
Error: unexpected '[' in "["
> hashtag.regex <- perl("(?<=^|\\s)#\\S+")
> hashtags <- str_extract_all(string, hashtag.regex)
> print(hashtags)
[[1]]
[1] "#olmpicrings" "#towerbridge" "#london2012" 
like image 970
Adedoyin-Olowe Mariam Avatar asked Dec 15 '22 20:12

Adedoyin-Olowe Mariam


1 Answers

Using regmatches and gregexpr this gives you a list with hashtags per tweet, assuming hastag is of format # followed by any number of letters or digits (I am not that familiar with twitter):

foo <- c("RddzAlejandra: RT @NiallOfficial: What a day for @johnJoeNevin ! Sooo proud t have been there to see him at #London2012 and here in mgar #MullingarShuffle","BPOInsight: RT @atos: Atos completes delivery of key IT systems for London 2012 Olympic Games http://t.co/Modkyo2R #london2012","BloombergWest: The #Olympics sets a ratings record for #NBC, with 219M viewers tuning in. http://t.co/scGzIXBp #london2012 #tech")

regmatches(foo,gregexpr("#(\\d|\\w)+",foo))

Returns:

[[1]]
[1] "#London2012"       "#MullingarShuffle"

[[2]]
[1] "#london2012"

[[3]]
[1] "#Olympics"   "#NBC"        "#london2012" "#tech"  
like image 59
Sacha Epskamp Avatar answered Jan 11 '23 01:01

Sacha Epskamp