【问题标题】:converting a nested list of userAccts and tweets to a dataframe [r]将 userAccts 和 tweets 的嵌套列表转换为数据框 [r]
【发布时间】:2018-02-14 03:03:00
【问题描述】:

我有一个 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 数据框的有效方法?

【问题讨论】:

  • 如果列表中包含长度不等的元素,则无法将其展平为数据帧,因为数据帧被定义为具有相等长度的列。这是我从列表开始时用来了解 purrr 的一个很好的资源:@​​987654321@
  • 我建议使用 rtweet 包而不是 twitteR。它有几个好处,特别是更容易进行身份验证和以格式良好、易于使用的数据帧返回数据。

标签: r list dataframe nested


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    这里,Botlist 是一个包含 Twitter 帐户名称的字符向量。 botdetails 将返回一个数据帧列表,您可以使用 plyr 包中的 rbind.fill() 函数组合这些数据帧。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多