在R语言中收集带地理编码的含Trump相关内容的推文
Hey there! I see you're trying to pull geocoded tweets related to Trump but coming up empty—let's break down the issues and fix this step by step.
First: Ditch tweetR for rtweet
The tweetR package is no longer maintained and doesn't support the latest Twitter API v2, which is likely a big reason you're not getting results. The modern, supported alternative is rtweet—it's actively updated and works with Twitter's current API ecosystem.
Fixing Your Search & Geocoding
Here's a revised workflow that should get you the geocoded tweets you need:
1. Install & Load rtweet
First, set up the package:
install.packages("rtweet") library(rtweet)
2. Authenticate with Twitter API
You'll need a Twitter Developer account (free for basic use) to get API keys. Run this command to walk through the authentication setup:
auth_setup_default()
Follow the prompts to enter your API key, API secret key, and access token/secret (you can get these from your Twitter Developer Dashboard).
3. Optimized Search Query
Your original search syntax is redundant (Twitter search is case-insensitive), and we'll adjust parameters to prioritize geocoded tweets:
# Search for Trump-related tweets with geocoding, centered on Atlanta (1000mi radius) tweets <- search_tweets( q = "trump OR #trump", n = 500, # Increase the number of tweets to account for low geocoded tweet density lang = "en", geocode = lookup_coords("Atlanta, GA", miles = 1000), # Easier than manual coordinates include_rts = FALSE, # Optional: Exclude retweets to focus on original content geocode_granularity = "place" # Ensures we pull tweets with valid place/geo data )
4. Filter for Only Geocoded Tweets
Not all tweets in the results will have geocoding, so filter to keep only the ones that do:
geocoded_tweets <- subset(tweets, !is.na(geo_coords)) # Check how many you got nrow(geocoded_tweets)
5. Prep Data for Mapping
Extract latitude/longitude for mapping with:
geocoded_tweets <- lat_lng(geocoded_tweets)
Now you can use packages like ggplot2 or leaflet to plot these points on a map.
Common Pitfalls to Avoid
- Low Geocoded Tweet Density: Most users don't enable location sharing on Twitter, so you may need to increase
nor widen your geographic radius to get more results. - API Limits: The free Twitter API tier has limits on how many tweets you can pull per request and per day—if you hit a limit, wait a bit or adjust
ndown. - Outdated Package: Again,
tweetRis deprecated, so switching tortweetis non-negotiable for reliable results.
内容的提问来源于stack exchange,提问作者Patrick Harris

