如何使用R生成大型IP列表的国家/地区名称?

时间:2016-10-20 22:41:56

标签: r dataset data-science

我的数据集包含1列但是有很多行。该列包含大量公共IP地址。因此,可以使用像{({3}}这样的网站从这些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")

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

1 个答案:

答案 0 :(得分:1)

最后用“rgeolocate”以更快的方式解决了这个问题&#39; rgeolocate&#39;和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")