Как преобразовать результаты SearchTwitter (из библиотеки (Twitter)) в данные. Слаба?
Вопрос
Я работаю над сохранением поиска в твиттере в базу данных (SQL Server) и получаю ошибку при выводе результатов поиска из Twitter.
Если я выполню:
library(twitteR)
puppy <- as.data.frame(searchTwitter("puppy", session=getCurlHandle(),num=100))
Я получаю ошибку:
Error in as.data.frame.default(x[[i]], optional = TRUE) :
cannot coerce class structure("status", package = "twitteR") into a data.frame
Это важно, потому что для использования RODBC добавить это к таблице с помощью SQLSave, она должна быть данных. По крайней мере, это сообщение об ошибке, которое я получил:
Error in sqlSave(localSQLServer, puppy, tablename = "puppy_staging", :
should be a data frame
Таким образом, у кого-нибудь есть какие-либо предложения о том, как привлечь список данных. Crame или как я могу загрузить список через RODBC?
Моя заключающая цель - иметь таблицу, которая отражает структуру значений, возвращаемых SechLeTwitter. Вот пример того, что я пытаюсь получить и загрузить:
library(twitteR)
puppy <- searchTwitter("puppy", session=getCurlHandle(),num=2)
str(puppy)
List of 2
$ :Formal class 'status' [package "twitteR"] with 10 slots
.. ..@ text : chr "beautifull and kc reg Beagle Mix for rehomes: This little puppy is looking for a new loving family wh... http://bit.ly/9stN7V "| __truncated__
.. ..@ favorited : logi FALSE
.. ..@ replyToSN : chr(0)
.. ..@ created : chr "Wed, 16 Jun 2010 19:04:03 +0000"
.. ..@ truncated : logi FALSE
.. ..@ replyToSID : num(0)
.. ..@ id : num 1.63e+10
.. ..@ replyToUID : num(0)
.. ..@ statusSource: chr "<a href="http://twitterfeed.com" rel="nofollow">twitterfeed</a>"
.. ..@ screenName : chr "puppy_ads"
$ :Formal class 'status' [package "twitteR"] with 10 slots
.. ..@ text : chr "the cutest puppy followed me on my walk, my grandma won't let me keep it. taking it to the pound sadface"
.. ..@ favorited : logi FALSE
.. ..@ replyToSN : chr(0)
.. ..@ created : chr "Wed, 16 Jun 2010 19:04:01 +0000"
.. ..@ truncated : logi FALSE
.. ..@ replyToSID : num(0)
.. ..@ id : num 1.63e+10
.. ..@ replyToUID : num(0)
.. ..@ statusSource: chr "<a href="http://blackberry.com/twitter" rel="nofollow">Twitter for BlackBerry®</a>"
.. ..@ screenName : chr "iamsweaters"
Поэтому я думаю, что данные. Карм щенка должен иметь имена столбцов, такие как:
- text
- favorited
- replytoSN
- created
- truncated
- replytoSID
- id
- replytoUID
- statusSource
- screenName
Решение
Попробуй это:
ldply(searchTwitter("#rstats", n=100), text)
Twitter возвращает класс S4, поэтому вам нужно либо использовать один из функций его помощника, либо справиться напрямую с его слотами. Вы можете увидеть слоты, используя unclass()
, например:
unclass(searchTwitter("#rstats", n=100)[[1]])
Эти слоты могут быть доступны непосредственно, когда я делаю выше, используя связанные функции (из справки Twitter:? Statussource):
text Returns the text of the status favorited Returns the favorited information for the status replyToSN Returns the replyToSN slot for this status created Retrieves the creation time of this status truncated Returns the truncated information for this status replyToSID Returns the replyToSID slot for this status id Returns the id of this status replyToUID Returns the replyToUID slot for this status statusSource Returns the status source for this status
Как я уже упоминал, это мое понимание, что вам придется указать каждую из этих полей себя на выходе. Вот пример с использованием двух полей:
> head(ldply(searchTwitter("#rstats", n=100),
function(x) data.frame(text=text(x), favorited=favorited(x))))
text
1 @statalgo how does that actually work? does it share mem between #rstats and postgresql?
2 @jaredlander Have you looked at PL/R? You can call #rstats from PostgreSQL: http://www.joeconway.com/plr/.
3 @CMastication I was hoping for a cool way to keep data in a DB and run the normal #rstats off that. Maybe a translator from R to SQL code.
4 The distribution of online data usage: AT&T has recently announced it will no longer http://goo.gl/fb/eTywd #rstat
5 @jaredlander not that I know of. Closest is sqldf package which allows #rstats and sqlite to share mem so transferring from DB to df is fast
6 @CMastication Can #rstats run on data in a DB?Not loading it in2 a dataframe or running SQL cmds but treating the DB as if it wr a dataframe
favorited
1 FALSE
2 FALSE
3 FALSE
4 FALSE
5 FALSE
6 FALSE
Вы можете превратить это в функцию, если вы намереваетесь часто делать это.
Другие советы
Я использую этот код, который я нашел из http://blog.ouseful.info/2011/11/09/getting-started-with-twitter-analysis-in-r/ Данное назад:
#get data
tws<-searchTwitter('#keyword',n=10)
#make data frame
df <- do.call("rbind", lapply(tws, as.data.frame))
#write to csv file (or your RODBC code)
write.csv(df,file="twitterList.csv")
Я знаю, что это старый вопрос, но все же, вот то, что я думаю, это «современная» версия для решения этого. Просто используйте функцию twListToDf
gvegayon <- getUser("gvegayon")
timeline <- userTimeline(gvegayon,n=400)
tl <- twListToDF(timeline)
Надеюсь, поможет
Для тех, кто работает в той же проблеме, я делал, что получила ошибку, говоря
Error in as.double(y) : cannot coerce type 'S4' to vector of type 'double'
Я просто изменил слово текст в
ldply(searchTwitter("#rstats", n=100), text)
к stustustext, как так:
ldply(searchTwitter("#rstats", n=100), statusText)
Просто дружелюбное голова-вверх: P
Вот хорошая функция, чтобы преобразовать его в DF.
TweetFrame<-function(searchTerm, maxTweets)
{
tweetList<-searchTwitter(searchTerm,n=maxTweets)
return(do.call("rbind",lapply(tweetList,as.data.frame)))
}
Используйте это как:
tweets <- TweetFrame(" ", n)
То twitteR
Пакет теперь включает в себя функцию twListToDF
Это сделает это для вас.
puppy_table <- twListToDF(puppy)