使用R挖掘Twitter数据:过滤回复与转推的查询失效求助
Looks like you're hitting a common snag with the twitteR package's handling of Twitter's search filters. Let's break down why your combined filter isn't working, and walk through actionable fixes:
Why the combined filter fails
The searchTwitter() function from the twitteR package is no longer actively maintained, and it doesn't reliably parse or pass through the full set of Twitter's standard search operators to the API. That's why adding -filter:retweets broke your existing -filter:replies logic too— the older package can't properly handle multiple filter operators together.
Solution 1: Switch to the rtweet package (Recommended)
For modern Twitter API access in R, the rtweet package is the official, supported replacement for twitteR. It fully respects Twitter's search operators, so your original filter string will work exactly as intended:
library(rtweet) # First set up authentication (follow the prompts to log in with your Twitter account) auth_setup_default() # Run the search with both filters tweets <- search_tweets( q = "eurovision -filter:replies -filter:retweets", n = 200, lang = "en" ) # Preview the filtered original tweets head(tweets)
This will return only original English tweets about Eurovision, excluding both replies and retweets as expected.
Solution 2: Manual filtering with twitteR (if you need to stick with it)
If you can't switch packages right now, you can fetch tweets with your working -filter:replies query first, then manually filter out retweets using the tweet data's built-in flag:
library(twitteR) # Fetch tweets with reply filter active keyword = "eurovision -filter:replies" tweets = searchTwitter(keyword, n = 200, lang = 'en') # Convert the tweet list to a data frame for easier filtering tweets_df <- twListToDF(tweets) # Filter out retweets (the `isRetweet` column marks retweets as TRUE) filtered_tweets <- tweets_df[!tweets_df$isRetweet, ] # Verify the results (count should drop if retweets were present) nrow(filtered_tweets)
This workaround works because the isRetweet column in the data frame explicitly flags retweets, letting you exclude them directly in R.
Key note
Twitter's standard search operators (-filter:replies, -filter:retweets) are indeed correct— the issue lies with the outdated twitteR package's ability to handle them. Upgrading to rtweet will prevent similar issues and give you access to more up-to-date Twitter API features.
内容的提问来源于stack exchange,提问作者Birgen Vermang

