Retweet Network

Loading JSON file

#install.packages(streamR)
library(streamR); library(tidyverse)

file <- "../data/stream/stream_got.json"
#file <- "~/Dropbox (UNC Charlotte)/summer-2017-social-media-workshop/data/stream/stream_got.json"

#?parseTweets
tweets <- parseTweets(tweets = file)

Creating a Retweet Network

In this example, we’ll create a retweet network. This snippet of code was from Pablo Barbera, who created the streamR package and who has phenomenal R materials for analyzing Twitter (highly recommend his GitHub!).

library(igraph)

# regular expression -- get only tweets that have "RT @"
rts <- tweets[grep("RT @", tweets$text),]

edges <- data.frame(
  node1 = rts$screen_name,
  node2 = gsub('.*RT @([a-zA-Z0-9_]+):? ?.*', rts$text, repl="\\1"),
  stringsAsFactors=F
)

g <- graph_from_data_frame(d=edges, directed=TRUE)

Now we have a network as a igraph object g.

Let’s run some basic network stats, e.g. find total number of connections.

degTotal <- degree(g, mode = "total")
degTotal <- degTotal[order(degTotal, decreasing = T)]

head(degTotal, n = 10)
##     333903271 GameOfThrones      LordSnow virginiakimba Thrones_Memes 
##           157            99            88            85            60 
##      Daenerys   ItsGoTQuote        ruhtyt OriginalFunko      REDbySFR 
##            44            31            15            14            11

Alternatively, since this is a directed network, we can find who did the most retweets (i.e., retweeted others).

degOut <- degree(g, mode = "out")
degOut <- degOut[order(degOut, decreasing = T)]

head(degOut, n = 10)
##      MookmixCz   AlitlayArisa  Shawn_DAGamer       kathmego    redondojeje 
##              8              7              5              5              5 
## mandyfreebird1  jack_son_five        lilyhuj      heyyouapp          lik5n 
##              5              5              5              5              5

Remember – our dataset was only for 10 mins. So those people did a lot of #gameofthrones retweets in only 10 minutes.

Further, we can find who was retweeted the most.

degIn <- degree(g, mode = "in")
degIn <- degIn[order(degIn, decreasing = T)]

head(degIn, n = 10)
##     333903271 GameOfThrones      LordSnow virginiakimba Thrones_Memes 
##           156            99            88            85            60 
##      Daenerys   ItsGoTQuote OriginalFunko        ruhtyt          9GAG 
##            44            31            14            12            11

Let’s instead observe the network using visNetwork, a HTMLWidget

library(visNetwork)

V(g)$size <- 10

visIgraph(g) %>% 
  visInteraction(navigationButtons = TRUE) 

However, things are a bit “squished” together. An important property of social networks is to alter the layout.

For example, we can set a property to add in “physics”.

visIgraph(g) %>% 
  visInteraction(navigationButtons = TRUE) %>%
  visIgraphLayout("physics" = TRUE)

We can also change the size of the nodes to correspond to the number of (total) degrees.

V(g)$size <- log(degTotal) +1

visIgraph(g) %>% 
  visInteraction(navigationButtons = TRUE) %>%
  visIgraphLayout("physics" = TRUE)

Just for fun, we can use another HTMLWidget edgebundler to create a different type of network.

#install.packages("edgebundleR")
library(edgebundleR)

edgebundle(g, fontsize = 6, directed = TRUE)
youknowsNOTHINGkenzyaaaaLucasDmitrukandygsgNicoleOjedaADirtyDaveAsh_Siobhan85_FuckDistractedhoopsxwildeanais_mklgsleepieundiesMookmixCzdaubnrauBD192937012ladysaraghitoonnnnandy_tilapia_francorios_Andalhue9scartssuWhiskeyLeifTxrgxryenraetunechiP_Edwards8Raf_GevDavidKraeglremarimmorenaKa8etosKomposMatiasGarnettretrosviviGammaLizardASodini_22marysmachinlaulaulau0106PratyushiJ_iiomii_lovatos_kingdomcopy_livesillyanshePetrovaGHAhmetHBasflake_huntr007ArminVanB6tony_aicvetos1WorkinginRadioOmarrH19Beansshamquidnonclibradragon2CaryysjonessAagriyaRajlevisinho18WIDOWYSCARbassss_sskyblouharryafxckingstarkGuadaBarquineroTr0ubl3423SoulRlhrdavantlannesDGwendalTamiFelizCamMTLgirlnv1515josephschroersofia_tsousaJaxxie_NastySplatterHollidayBS71CaseyCscrumptonPraiz_jrMeraAdel11simon_lindsellros_malaiPolillaHLCatchMeNickiMaColeenIsabelgargichaturved1annavarvedoAhm3d_Salahpax4d4llyenzyr_graileSKYH0WELLana_vrasouanaadsgio_logieDmMsu80archjosancd15plazmatiLa_Pte_FadetteKirskirsmothisispairhzwnrhoe4blackpinkBruschetNJusCallMeWillgregorius1982mohamedfaliluKingShinyGroudoSerraAmadeoASChoucasignofshellodyIliaWaditierra_whitmoreNicoLarkinYoungandsosadgam_ggamShawn_DAGamerkayla_jaskulskiJcsTwittahmsidusogieKateOHareWritesKILO__14leeza774liz__fisherEstelleuuhrebecalara97mr_sjpattersonunicornassesmaritxu_mariesuneyd_jerrydids_18kellskathleen_Swaguilar_33_rafaamor_camzzuadajesusbaguetteleowsydneyVenthiaTdjatjreomintchipcookie3laughofhoranxShowEdshowfawpp36fraserstarksCanijaChanVickyPlataux333903271Carlito_1991_thatIndianKid17EmmanuelC2310AhmedLachalaJustAn54Hv_boy_BbcTheDreamerdextinr_JoshuaBoukarDeliipPrezlord_shubham5woodpriRoom1ServiceStardust_AppkarmmybugM_AwaisnazeerZoeperJbellabicepsGauchebagGirl_bezimieniabt3022monpanaAmahazolikeVICDICTIVELisaDraculeaJohn0NeilljuliofcportocaraengracadaTheLonelySithdanielhgmxdemirhan_ilkerGumb9lldanicakatreenaodmenenemavajdeceo_0001momolicious22LinaGeydorstellatirelli88richieday85Alicia_Kathine_00024032JakeStraussOn_Ur_Marclecomtephynabiyorke_KarinLindstrom1ChexTexMixmm_broadwaysqniiiReguxAlanizAaliyaheartbeatKhadeeja_Dadagracieb9412yvelastanm33linalostkailkathmegoanissiraevem1lde08btikaudzusmiling_lytodori3valentina_miaah3minimarac00perlovegunaheartredondojejeju0dyp8mes000000000001110tamekia_ajustintimeOOed1aniianati1ahkumi1anaukmariashivanuihatsumnoolivierapataylerhefreshkayleehayasu34mandari6eli23bm1l1rsenkyosakkilindawill_iamn0icxeleparalayamiri2subaki5anajjnyt1kat1kajan2non1l0adebbiedoublettfb_jacktanyaqiinhaarussomandyfreebird1jack_son_fivelilyhujheyyouappmara1ys1ntabchloeesus0fla0marievonbeneker1tapkaebitbailiashiasteve1ellensl1lmmagdaeasah6yuknewsebrunliimonikahottekurokihiakowhitebettysMamicVlinadbgjoyvints0am8ersunsheryan9brezJasonWe75824821milllenacView_Patimapornruhtyttiftanpos11achemitwmelani3rtyleronemopriaciaLakerGirlBlujaysurzroii1ssadbbmonicappocamposginlimtsanusliaunewseanntztjoserwalkerlik5nela1inecaseytthaAntonioluiz_1kikecanario10Nazzy415MadzixkcjlNB_BEAST14hxhmaniac_daetheriuscviijetic22CarefulMonsteroojuliaaRaulCarayol_Erika_RioszklineForrezDavinabastiplay75Axechuckerbobwarren66karimfaramawyBushrahussain5501_1__1001_1davidbrock84INMGLDLlaron501_IAMBATMAN_andreeaa_20juninhogrossi_Summer_acebeerjaaaaaCLAWXDevania0427urietakaraiSomto_Ibi_sexual_trashfertrayLouiseDeeannaFiumelegitshitsonjohn69nlmickeystewartludodero_MiniMaggie_rebekah_tarryMoonlight_BaeaenicolotassinariTheNickCostanzaDyal_el_amadeusraulson_DF_Chrissherookasemjgautam12j_kujiraTchinedvuAshleighRopaBeckhambinhoMarierchttB_BLVLnicolamarajlauraa_garau_yandraktatxevnoppon_winsu_surangNovachozofangirlnerdxxxbeyheelsoFleekaMarajsaveandearndor_edwardskanekatesdedekijanCHXNGNXYSPauBusssantoshdasiIbrahimmusashehthais_chsLeaveNARAalonedani8899abdoyamanySammie15090802MarisaLewiscerenyetkin_oceanriverzEnDaMoMubaa10Yoshi930102ewekamrlpsEmmanuelBethouxMontescoGHletcatapanjessicam908Oga_AceLindi_Veeclayherring15minellaminajanunderdogxoyourgaykhaleesifranfourcade2David_RazolaBeeorliciousgoofyvaldez1evontekarenchuu6rincondemarlauConnorrness4NDR3_K1K0OOgirdoRodrigoclarafromheavenjcobqwertyunygteminiedouAnonymouzPersonNavaPriscillaBlackDionysosmattmcwills18patidlilAdoraJuneHathaiHWWaitforit41RaliK11Tupfilover13RavFOX5Vegassb_bonmagssantiagooDjemaK20AmbinMnloalfrebarriosfannievazquezbmikebawdensidduishereATSocialMediaRTFlurishingQuirkbreezy2374ouatpercyvsssoapoulsonAaronbruscino1AleyScofielditsdanversnarshi03Mc_ChizzyBanagasaurrrRdPomiMrOlwethuinitialness3abdaallahNoctifexnicovaldez_pyJjeankelixFix_it_Ralphotaviovianna25XoRk0EkranellaNnpPnGBDaddyMyAngeljuliver_tomasDhinenGmccannjessica94ScienceCabaretsweetsufosBornHater_ReccstacyblomquistMaster_InanchisalomebouletUmmieBellopamelendjoelalvarezoaxasternenglazRASANDREMVSha_MooreDavidADSotillo_niinoi07betsy_is_funnythatmanutdladJoonyer77CloydKatieMariondudu74SofieImerKishTheFish6Smarrogantqueenharleenmsjuicyybabysydney_perdjooux23b8ad8424bc484datnewyorkfreshhdenslow96MischixfManxgedWHITEHARRYANGELCarleyChireakinjide_EtTuBritusanestezija5disveIocityBlackHorizonIrABlueMermaidbev_metallicamilimonade_hyunafireDarT_WoNefcmookHamdadelreySkrappzDoobierodrigoocoimbrarodrixswfelixhergoodnice__67yasseros007M0llyB3Aadoresjuan_andrej134568Rebecca_H5Rani_Anaisdoitagain200321Florrcorrea_TheMissYasminedbourdainAC_wright08Anniepty1edulcorantlauraamirnela12Osvaldo_PBitskamolzFM25000gzzbrieltofufriedxoskidMaryannKayalabthani501bigdc76KhoisaanStephenB17holt613REDbySFRGeffKillga_bteponymousgrtheonlyogechiicham76_M_AELYSmicmxxAlitlayArisaJulie_KavLe_manjSkilluminati629prettydamnninjalafissouSbeckettssmileDiegoarl_andpeg_gyB_C_MLAM777JamesHannah15chamasalmatracyscpmaath54390MutectorSepulcher67stephkartcos23das_ICH74clintzthaynalombaRaidsheezRetroLBarlowAniratac2699_H4rmony_dinysic2010CharlotteRudinRajendr74151788dianaegbiksRidh1ahmadorphe666BigMeechMandaBoonchuen_AudantiquePMLqopmmewthana_aenyrsJesusManuelCSEL_FIASCO77fingkishermaridlavTheNewBlaackisabellacaputo2MrRizos_Serenblackityrosee_schererVintechGxPatina_LegendsRTsmemssselieMaia_Rua_carolisebjdpmaragonnoeli110AdemolaKosokoexsunxo24ZachLeherrFairPatteerayannamaravilhadanclark63bitsideaskitzhuoritaasalvatoreeg_savgutyputy86MaronTodaiDeeLiRiouS13LaFille_Du_FootYannik_Silvaroxanedani39MrAmbroseToYoufch4ngvaljozevippyshrmAliiSamatJesusDanGuerrafree_ticklesmarmeladalis3AsharaBroxPichu974RobertNkosinat2bangsatsatDreamiizCElodie_BGTnirachatalpprangpranggvishaliiiikitapatmiyafreedom_gunDmethodmanCon_MackkshutdownchannelryyyshhThara_saWhittenWillDavidDobbs97chespinpinHeyLeezyEnClaudeNeufabdallahesnathantrevenenLeoPartesanoSzlevin77cycalina_Ramallets7Hollaboy3giftedphanKingKingpetertherealjibolayiannislioMercurioPsiChaz623_rfashamJohannesIsiklabliisaurdanhorningangelyth21captn_punchjasyygeeohimebeaTheJoseGrandeeobearavkbhatFideo_con_Pestoadrp03RomainWtkKyuketsuki182MukdadMohamadfilipem007Super_Vittotilyayeva12bea_shalllmariamera_6Kohnye3angETFmiichellevejarSoltaniMorteza7AnanthAdiseshMcChicho92jtinoco001Jpppal5tul_tulayaizaczetsuLe_Fils_De_DieuarkayscreationsminnesotaragerDaniaAlBashirphiloneill14alveee_edgeAnaSofiaFerreiMarkfnCodyKamleiathespacelvSteveO_WriterbiserdimitrovbrevamoOle4kaMsIMujallidBartuCLKNCurtisFortierDnevnikCecamckenziesweetyMaddieClaire123Hez_PezrihanaESjpalacpacatomjenkinsemiliaeclarketrishwalkcrsamyrightside5arcenfroseph25royhyzhflashy24loemmie87mrs_plastic_bagsellecapsssSsNinisAtemRMMichaelOkoye12stargirlngc123Alhemicar__MermaidLei_HanaShi_arab_boice4MichelaGazzillimrsNeuerhohomarich06samchios17RingofLibertyMarkeel1234dieoleaSIO_gwlapkultItsDaniBiersackfseiseverywherehilariospapaverMumbaiGluttonjstivy14Alexcasas26aladaziousAbhi_Ananthutrbu56emo_frankiesubha_iyengarahmad_69696juanoliveraoklouholdon_afzal_izharMichaelANewhousFunko_fuel23LM16612718rcwoolseySalavatUnitedDesnecessarah___xwhyimx__ohmynj_Preshanta_o_ismail31666metalkingZaimNashruddinMelaninMonroexoHausOfAjexayotundeaaMizu_no_HanaDreaSimss39am_87ChiaShibaInuTayoMadeYouLookbyrbyrloridietzdutak90anyshfsuleybashircuyper_paulif_chukwuprincesserjaneManneLessEyed_by_EstradaNelyos_HSbrendala_15w_wertyyaDynnaStark_pdonghunmsluvillafItsGoTQuoteDaenerysGoT_TyrionLordSnowmichaelkelly93GameOfThronesHerNameIsFerThrones_MemesaimasmaIFalknerKylebobbiesgarciaAmitYad85976191JaskiLannisterPannminORawristbillboardTheGrandTestaddictoofAngelaBelcaminoOzzyManReviewsWiCnethashtagameenRiotKobe9XOIndiaGossipGunTheReaderThairzye42IncWorkopolisskyatlanticSylviaObellPage_GoTzavvirishibagreejohnbradleywestMaisie_Williamsmaisierp7_rpJoeMilordPreviouslySerieHammadHumayun19GAGDartagnansFRJoyAnnReidACR_POKERFakeBarneyKSROriginalFunkoROYALIPTV9MildlyAmusedsa__diajuegodtronosLAIzzyx91NathanSykesMargaery_TyrellAmazingPhilDinamyte007MattBarrietokenblackchickKarlTatawifeZoneActuFRsivapron_farMosalakaeMTKITN_JonSnowVictoriaAmyVIMC_LeedsLePointPopVirginRadiofrIndieWireAustinCTweetsGoTthings_FamilyTheater1hmvtweetsDavidCaspibrendamaiyTheGamer2323biihfrancaCharlie_PotterdanielhowellTrazztobrownjenjenTheStevenEdwardgabriel_TheCodeGHLPodcastTVwebStrummer_86FjanwiriMinifigsMegiovanny175TranceCosmostutalittlebearQueen_Daenerys_Rouvafemegapollz2SopaguadaTheDMLabydyabancidiziTheHPFactsnuovamusica_kateejamiesonComplexRyanKGreenelea00starr00ndyjaninenattvickltysimg0nakellyroosveTeePlus5JHallComicsArya_No1ElPirataFrikikatnissenpanemManFromWaltaxiaPhanclanabinashjena432fusetvzach_goinsyourenotguiltyChaChaGeekGirldarth_daisy_RealDollyFoxvale_gstsamfickmanNilzenburgerCeceDiorDoLLMudkipMamaYoungMoneySiteroberta_daros_Sakun_SDHBO_UKzhiczGameOfThroneGuySiti_sjbbmeenamalviyGame_Of_Deadkurt_kemEmilie__Caronimdariookfrancy_flomunicpfJulesGrandinemma_popcornCanalFootClublilgeezapetaTomWitwickyMOREFOX5hosam_issaBasileiaSnowAwesomEmergencywantedphotosukClothCatAnimJonWinterfallthiago_pNalyeVanyaaras_bayramdaradailylukewalthamchpiras87sensitivscisparklingshoesJawiinLIRIKSandrixMCeddsguitarBellaRamseyBAHjournalistsyndromenaEWCosmopolitanTHRHookedOnGoTSIDD_tHe_ARTHAMarlaWickedCultNClickBlackMajiiks2ll2hheyheyandre_artSomeguy137_if97businessinsidercineloisirsJustAJaguarxavecbdlJro_Soumahonerdistvrij_nederlandComicBookGrrlManUtdIradexthedarksea1LeadersNG3AM__MO2MoonTheSeriesViscorusGamingLeSadPandaNicolasHortusLass2foisSofiazurro97EmekaGiftMongoleardentbearMSFTnews_Roundo_Nick_Marseilmax_miguNamtal1411GtStevensonleolovesrandommotelsonthemoonUKfilmredcarpetesquirebelle_reveurPixelsRepublicMariPi__unicornsasGOTseries_NewzAnnaCerasJackPosobiecRou_Diaztladyinthetowereatingb00ksBlackGirlNerdsbrfootballLady_OomiesShimmerAndClinkBingNiceNEZcondemnbrosvirginiakimbaBasaranOrhunFittenTrimh011xcafemontenegroMudchalinsutabnaellievhallThePokeessence_mePITCHAPHAN_BMSportsFanaticosstargarienJYHeffect_hedaleksamay_i_beWBLooneyTuneslaterceraWightsKingSargylanaPotterMonicaYadav08Of_CheburashkaKimberlyClose91kimrrenfrorischisseurColonelCadavernalicaptswanARTEfrAlleluyaChuu

There are a TON of other ways to customize networks. I strongly recommend users who are interested in analyzing social networks to check out Katya Ognyanova’s phenomenal network tutorial for a wider range of options.

Challenge: Creating other Network

Reply Network (Easy)

For this challenge, you’ll need to create a reply network.

For this, you’ll need to use similar code in rows 111-117. However, instead of focusing on the RT’s, you’ll simply need to create the edge list from two fields: screen_name (from) and in_reply_to_screen_name.

Like the RT example, you need to first create a subset of the tweets to only include tweets that include a reply. You can use the subset function (type ?subset to look it up) along with the is.na() function to identify only tweets that have a reply. Make sure to take the “negation” (!) of the is.na function.

See the attached R code (challenge-solution.R) for the solution.

## write your response here

Mention Networks (Hard/just FYI)

If you’re able to complete the first task, try to run this code for a mention network

Code from this section is from cosmopolitanvan’s RPubs tutorial, which is another great resource.

# regular expression -- get only tweets that have "@" (i.e., mention)
mention <- tweets[grep("@", tweets$text),]

names <- lapply(mention$text, function(tx) {
    matches = gregexpr('@[^([:blank:]|[:punct:])]+', tx)[[1]]
    sapply(seq_along(matches), function(i) 
      substr(tx, matches[i] + 1, matches[i] + attr(matches, 'match.length')[i] - 1))
  })

edges3 = 
  lapply(seq_along(mention$text), function(i) {
    if(names[[i]] == '')  
      return(NULL)
    lapply(names[[i]], function(m)
      c(node1 = as.character(mention$screen_name[i]), node2 = m)) %>%
      do.call(rbind, .) %>% as.data.frame()
  }) %>% 
  do.call(rbind, .) %>%
  count(tolower(node1), tolower(node2))

g3 <- graph_from_data_frame(d = edges3, directed = T)

V(g3)$size <- 10

visIgraph(g3) %>% 
  visInteraction(navigationButtons = TRUE) %>%
  visIgraphLayout("physics" = TRUE)