如何使用R为大量IP生成国家名称?

如何使用R为大量IP生成国家名称?,r,dataset,data-science,R,Dataset,Data Science,我有一个数据集,其中包含1列,但行数巨大。该列包含大量公共IP地址。因此,可以使用以下站点从这些IP获取地理位置(希望生成一列国家名称,其中包含行中每个IP的国家名称。以下是我的简单方法- library(XML) #Import your list of IPs ip.addresses <- read.csv("ip-address.csv") #This is my API api.url <- "http://freegeoip.net/xml/" #Appending

我有一个数据集,其中包含1列,但行数巨大。该列包含大量公共IP地址。因此,可以使用以下站点从这些IP获取地理位置(希望生成一列国家名称,其中包含行中每个IP的国家名称。以下是我的简单方法-

library(XML)

#Import your list of IPs
ip.addresses <- read.csv("ip-address.csv")

#This is my API
api.url <- "http://freegeoip.net/xml/"

#Appending API URL before each of the IPs
api.with.ip <- paste(api.url, ip.addresses$IP.Addresses ,sep="")

#Creating an empty vector for collecting the country names
country.vec <- c()

#Running a for loop to parse country name for each IP
for(i in api.with.ip)
{
    #Using xmlParse & xmlToList to extract IP information
    data <- xmlParse(i)
    xml.data <- xmlToList(data)

    #Selecting only Country Name by using xml.data$CountryName
    #If Country Name is NULL then putting NA
    if(is.null(xml.data$CountryName)){
      country.vec <- c(country.vec, NA)
    }
    else{
      country.vec <- c(country.vec, xml.data$CountryName)
    }
}

#Combining IPs with its corresponding country names into a dataframe
result <- data.frame(ip.addresses,country.vec)
colnames(result) <- c("IP Address", "Country")

#Exporting the dataframe as csv file
write.csv(result, "IP_to_Location.csv")
库(XML)
#导入您的IP列表

ip.addresses终于用“rgeolotate”和mmdb以更快的方式解决了这个问题

library(rgeolocate)

setwd("/home/imran/Documents/")

ipdf <- read.csv("IP_Address.csv")
ipmmdb <- system.file("extdata","GeoLite2-Country.mmdb", package = "rgeolocate")
results <- maxmind(ipdf$IP.Address, ipmmdb,"country_name")

export.results <- data.frame(ipdf$IP.Address, results$country_name)
colnames(export.results) <- c("IP Address", "Country")

write.csv(export.results, "IP_to_Locationmmdb.csv")
库(rgeolotate)
setwd(“/home/imran/Documents/”)

ipdf From:默认情况下,每小时最多允许10000次查询。一旦达到此限制,您的所有请求都将导致HTTP 403,禁止,直到您的配额被清除…所以不要太快。您可以使用每个国家/地区的IP范围从缩小请求数只需使用
rgeolocate
和免费的maxmind GeoIP 2国家/地区而且,认真地看一下
purr
vs
for
循环。