将嵌套的userAccts和tweets列表转换为数据帧[r]

时间:2017-09-05 18:38:19

标签: r list dataframe nested

我有一个userAccts和tweets的嵌套列表,结构(在R中)在下面。

> str(botdetails[[1]][[100]])
Reference class 'status' [package "twitteR"] with 17 fields
 $ text         : chr "RT @jeremyslevin: 30% of the Bush tax cuts-which wrote the book on giveaways to the rich-went to the 1%. Trump "| __truncated__
 $ favorited    : logi FALSE
 $ favoriteCount: num 0
 $ replyToSN    : chr(0) 
 $ created      : POSIXct[1:1], format: "2017-09-02 07:59:32"
 $ truncated    : logi FALSE
 $ replyToSID   : chr(0) 
 $ id           : chr "903890119945359360"
 $ replyToUID   : chr(0) 
 $ statusSource : chr "<a href=\"http://twitter.com/download/android\" rel=\"nofollow\">Twitter for Android</a>"
 $ screenName   : chr "Monalisazelf"
 $ retweetCount : num 252
 $ isRetweet    : logi TRUE
 $ retweeted    : logi FALSE
 $ longitude    : chr(0) 
 $ latitude     : chr(0) 
 $ urls         :'data.frame':  0 obs. of  4 variables:
  ..$ url         : chr(0) 
  ..$ expanded_url: chr(0) 
  ..$ dispaly_url : chr(0) 
  ..$ indices     : num(0) 
 and 53 methods, of which 39 are  possibly relevant:
   getCreated, getFavoriteCount, getFavorited, getId, getIsRetweet, getLatitude,
   getLongitude, getReplyToSID, getReplyToSN, getReplyToUID, getRetweetCount,
   getRetweeted, getRetweeters, getRetweets, getScreenName, getStatusSource, getText,
   getTruncated, getUrls, initialize, setCreated, setFavoriteCount, setFavorited, setId,
   setIsRetweet, setLatitude, setLongitude, setReplyToSID, setReplyToSN, setReplyToUID,
   setRetweetCount, setRetweeted, setScreenName, setStatusSource, setText, setTruncated,
   setUrls, toDataFrame, toDataFrame#twitterObj
> 

我的问题是尝试将嵌套列表转换为数据框, twListtoDF 给了我这个错误:

> twListToDF(botdetails)
Error in twListToDF(botdetails) : 
  Elements of twList are not of an appropriate class
> 

twListtoDF 的帮助页面将 status 列为该函数的相应类:

Details

The classes supported by this function are status, user, and directMessage.

有人能建议从这个嵌套列表中创建R数据帧的有效方法吗?

2 个答案:

答案 0 :(得分:0)

purrrjsonlite包都有flatten()个功能。 jsonlite版本可能最适合您的用途,因为我假设Twitter API返回一个JSON对象(并且purrr:flatten一次只删除一层递归)。

信息在这里:https://rdrr.io/cran/jsonlite/man/flatten.html

答案 1 :(得分:0)

我假设您正在尝试提取某些Twitter机器人帐户的用户信息。如果您要将所有这些信息作为数据框提取,请尝试以下操作:

botdetails <- map(Botlist[1:100], ~twListToDF(lookupUsers(.x)))
botdf <- rbind.fill(botdetails)

此处,Botlist是包含Twitter帐户名称的字符向量。 botdetails会返回一个数据框列表,您可以使用rbind.fill()包中的plyr函数将其合并。

相关问题