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

How to generate country names for a large list of IPs using R?

我有一个包含 1 列但包含大量行的数据集。该列包含大量 public 个 IP 地址。因此,可以使用像这样的网站从这些 IP 获取地理位置(http://freegeoip.net).I 想要生成一列国家/地区名称,其中包含行中每个 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")

但是由于我有大量的行,我使用 for 循环的方法非常慢。如何让这个过程更快?

终于用 'rgeolocate' 和 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")