无法得到推文的纬度和经度值

Fri*_*ten 3 r text-mining tm

我收集了一些推特数据:

#connect to twitter API
setup_twitter_oauth(consumer_key, consumer_secret, access_token, access_secret)

#set radius and amount of requests
N=200  # tweets to request from each query
S=200  # radius in miles

lats=c(38.9,40.7)
lons=c(-77,-74)

roger=do.call(rbind,lapply(1:length(lats), function(i) searchTwitter('Roger+Federer',
                                                                lang="en",n=N,resultType="recent",
                                                              geocode=paste  (lats[i],lons[i],paste0(S,"mi"),sep=","))))
Run Code Online (Sandbox Code Playgroud)

在此之后我完成了:

rogerlat=sapply(roger, function(x) as.numeric(x$getLatitude()))
rogerlat=sapply(rogerlat, function(z) ifelse(length(z)==0,NA,z))  

rogerlon=sapply(roger, function(x) as.numeric(x$getLongitude()))
rogerlon=sapply(rogerlon, function(z) ifelse(length(z)==0,NA,z))  

data=as.data.frame(cbind(lat=rogerlat,lon=rogerlon))
Run Code Online (Sandbox Code Playgroud)

现在我想获得所有具有long和lat值的推文:

data=filter(data, !is.na(lat),!is.na(lon))
lonlat=select(data,lon,lat)
Run Code Online (Sandbox Code Playgroud)

但是现在我只获得了NA值....对这里出了什么问题的任何想法?

Tch*_*hke 6

正如克里斯提到的那样,searchTwitter并没有返回推文的长篇大论.您可以通过转到twitteR文档来看到这一点,该文档告诉我们它返回一个status对象.

状态对象

向下滚动到状态对象,您可以看到包含11条信息,但是lat-long不是其中之一.但是,我们并没有完全丢失,因为返回了用户的屏幕名称.

如果我们查看用户对象,我们会看到用户的对象至少包含一个位置.

所以我可以考虑至少两种可能的解决方案,具体取决于您的用例.

解决方案1:提取用户的位置

# Search for recent Trump tweets #
tweets <- searchTwitter('Trump', lang="en",n=N,resultType="recent",
              geocode='38.9,-77,50mi')

# If you want, convert tweets to a data frame #
tweets.df <- twListToDF(tweets)

# Look up the users #
users <- lookupUsers(tweets.df$screenName)

# Convert users to a dataframe, look at their location#
users_df <- twListToDF(users)

table(users_df[1:10, 'location'])

                                       ? Texas  ? ALT.SEATTLE.INTERNET.UR.FACE 
                   2                            1                            1 
               Japan             Land of the Free                  New Orleans 
                   1                            1                            1 
  Springfield OR USA                United States                          USA 
                   1                            1                            1 

# Note that these will be the users' self-reported locations,
# so potentially they are not that useful
Run Code Online (Sandbox Code Playgroud)

解决方案2:半径有限的多次搜索

另一种解决方案是进行一系列重复搜索,以小半径增加纬度和经度.这样,您可以相对确定用户是否接近您指定的位置.