我有一个可能包含错误的facebook用户名列表。我想在很多方面调用getUsers并获得每个人有多少喜欢。如果getUsers遇到错误的用户名,我想从列表中删除它并再试一次。
我想在Rfacebook中这样做(但如果答案是我必须使用httr并自己编写GET请求,那就这样吧。)
load("fbCred.RData") # you will need a Facebook credential to execute this
library(Rfacebook)
fb_users <- c("brucespringsteen","coldplay")
fb_likes <- tryCatch(getUsers(users=fb_users,token=fbCred)$likes)
fb_likes # Returns: [1] 4807200 36768913
fb_users <- c("brucespringsteen","coldplay","This-Bad-Name-Will-Fail")
fb_likes <- tryCatch(getUsers(users=fb_users,token=fbCred)$likes)
# Returns:
# Error in callAPI(query, token) :
# (#803) Some of the aliases you requested do not exist: This-Bad-Name-Will-Fail
if(inherits(fb_likes,"error")){
# I want to remove the one that failed from the list of users and try again.
# But the callAPI error never makes it into fb_likes.
}
有没有办法在Rfacebook中做到这一点?如何检索坏用户的名称,以便我可以从列表中删除它并重试?
编辑:我知道我可以逐个遍历用户名。这是我目前的解决方法(使用adply)但需要更长的时间。
答案 0 :(得分:1)
错误属于&#34;尝试错误&#34;,而不是&#34;错误&#34;。此外,您需要使用try
,而不是tryCatch
:
fb_likes <- try(getUsers(users=fb_users,token=fbCred)$likes)
if(inherits(fb_likes, "try-error")) { ... }
应该有效。 tryCatch
更复杂,需要不同的结构,例如:
tryCatch(
fb_likes <- getUsers(users=fb_users,token=fbCred)$likes,
error=function(e) {
err.msg <- conditionMessage(e)
...
} )
答案 1 :(得分:0)
load("fbCred.RData") # you will need a Facebook credential to execute this
library(Rfacebook)
fb_users <- c("brucespringsteen","coldplay","This_Will_Fail","Bad_Bad_Bad")
fb_likes <- try(getUsers(users=fb_users,token=fbCred)$likes)
if(inherits(fb_likes,"try-error")){
bad_users <- unlist(strsplit(sub(".*exist\\:\\s+(.*)\\n$","\\1",
fb_likes[1]),split=","))
print(paste("These user names failed, removing:",
paste(bad_users,collapse=", ")))
fb_users <- setdiff(fb_users,bad_users)
fb_likes <- getUsers(users=fb_users,token=fbCred)$likes
}
print(data.frame(fb_users,fb_likes))
产生所需的输出:
[1] "These user names failed, removing: This_Will_Fail, Bad_Bad_Bad"
fb_users fb_likes
1 brucespringsteen 4808496
2 coldplay 36786558
要提取不良用户列表(使用正则表达式和strsplit),可以从geterrmessage()
开始(假设它是最后一个错误),但从“{1}”开始可能更可靠try-error
对象本身。然后我使用setdiff
删除不良用户。