如何从rtweet的get_friends返回的tibble列表中移除无效用户的空tibble
区分无效账号与零好友用户的解决方案
你遇到的问题核心是两种"空"tibble的本质区别:
- 无效/不存在的账号:返回的是0行0列的空tibble(连
user_id和friend_id列都没有) - 存在但零好友的用户:返回的是包含
user_id和friend_id列但0行的tibble
用nrow()判断会把这两种情况都误处理,所以我们需要通过列的存在性来区分它们,或者更稳妥的方式是先验证用户有效性再获取好友。
方案一:直接过滤现有列表中的无效空tibble
如果已经获取了好友列表,你可以通过检查每个tibble是否包含必要的两列(user_id和friend_id)来保留有效结果(包括零好友的用户):
library(purrr) library(rtweet) # 假设你的好友列表是friends_list filtered_friends <- friends_list %>% # 只保留包含user_id和friend_id列的tibble keep(~ all(c("user_id", "friend_id") %in% colnames(.x)))
这样操作后,那些0行0列的无效tibble会被过滤掉,而有列但0行的零好友用户tibble会被保留。
如果你想进一步标记零好友的用户,或者补充他们的原始user_id(因为0行的tibble里没有用户id),可以在获取好友时就绑定原始用户id:
# 假设core_users是你的核心用户id向量 friends_list <- map(core_users, function(user) { res <- get_friends(user) # 处理两种情况:无效账号(0列)或零好友(0行但有列) if (ncol(res) == 0) { # 无效账号,标记状态 tibble(user_id = user, friend_id = NA_character_, status = "account_not_found") } else if (nrow(res) == 0) { # 零好友用户,标记状态 tibble(user_id = user, friend_id = NA_character_, status = "no_friends") } else { # 有好友的用户,添加状态标记 mutate(res, status = "has_friends") } }) # 过滤掉无效账号,保留有效记录 valid_friends <- friends_list %>% bind_rows() %>% filter(status != "account_not_found")
方案二:先验证用户有效性(更可靠)
从根源上避免无效tibble的方法是,先通过lookup_users()检查核心用户是否存在,只对存在的用户调用get_friends():
# 1. 获取核心用户的详细信息,筛选出存在的用户 core_user_details <- lookup_users(core_users) existing_users <- core_user_details %>% filter(!is.na(user_id)) %>% # 不存在的用户user_id会是NA pull(user_id) # 2. 仅对存在的用户获取好友列表 friends_list <- map(existing_users, get_friends) # 3. 合并结果并补充零好友用户的记录 all_friends <- bind_rows(friends_list) # 找出零好友的用户(没有出现在all_friends中的存在用户) zero_friend_users <- tibble( user_id = existing_users[!existing_users %in% all_friends$user_id], friend_id = NA_character_, has_friends = FALSE ) # 合并最终数据 final_friends_data <- bind_rows( all_friends %>% mutate(has_friends = TRUE), zero_friend_users )
这种方法更可靠,因为它提前排除了无效账号,你不需要再处理那些无意义的空tibble,同时完整保留了零好友用户的记录。
内容的提问来源于stack exchange,提问作者Sunil Reddy
相关产品推荐
相关产品推荐

