如何从 get_friends 函数返回的 tibbles 列表中删除空 tibbles?

Sun*_*ddy 3 r list rtweet tibble

我正在使用packageget_friends函数来获取一组焦点用户的朋友rtweet列表,这些焦点用户是从 Twitter 讨论的参与者中抽取的。user_id该函数返回一个 tibbles 列表。

每个小标题都有两列 - 第一列包含焦点用户的列user_id,第二列包含user_id焦点用户朋友的列。由于每个用户的朋友数量不同,因此每个小标题中的行数不同。

我的问题:由于未知原因,一些焦点用户的帐户现在不存在。因此,该列表有空的 tibbles,如下所示:

> userFriends[[88]]
# A tibble: 0 x 0
Run Code Online (Sandbox Code Playgroud)

非空 tibble 看起来像这样:

> userFriends[2]
[[1]]
# A tibble: 32 x 2
                 user            user_id
                <chr>              <chr>
 1 777937999917096960           49510236
 2 777937999917096960           60489018
 3 777937999917096960         3190203961
 4 777937999917096960          118756393
 5 777937999917096960         2338104343
 6 777937999917096960          122453931
 7 777937999917096960          452830010
 8 777937999917096960           60937837
 9 777937999917096960 923106269761851392
10 777937999917096960          416882361
# ... with 22 more rows
Run Code Online (Sandbox Code Playgroud)

我希望我的代码能够识别这些空的小标题,并在没有这些小标题的情况下对列表进行子集化。

我使用nrow这些小标题上的函数来查找每个焦点用户拥有的朋友数量。

nFriends <- as.numeric(lapply(userFriends, nrow))
Run Code Online (Sandbox Code Playgroud)

我将该值为零的索引作为空 tibbles,并使用子集技术删除它们,如下所示:

nullIndex <- nFriends!=0
userFriendsFinal <- userFriends[nullIndex]
Run Code Online (Sandbox Code Playgroud)

目前这似乎有效。但通过这种方式,我还删除了零好友的用户(尽管可能性很小)以及不再存在或不再可通过 API 访问的用户。我想确保只删除那些无法访问或不存在的内容。请帮忙。

Cet*_*ttt 7

您好,您可以使用包discard中的函数purrr

这是一个小例子:

library(purrr)
mylist <- list( a = tibble(n = numeric()),
      b = tibble(n = 1:4))
discard(mylist, function(z) nrow(z) == 0)
$b
# A tibble: 4 x 1
      n
  <int>
1     1
2     2
3     3
4     4
Run Code Online (Sandbox Code Playgroud)