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

标签 r dataset data-science

我有一个包含 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")

关于r - 如何使用 R 为大量 IP 生成国家/地区名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40165670/

相关文章:

python - 如何在 Pandas 中创建 DataFrame

machine-learning - 机器学习哲学 : applying model to biased data

r - 在每次函数迭代时动态更新输入数据帧,无需全局分配

r - 对 data.frame 进行子集化时对负索引的解释

python - 如何像 MNIST 数据集一样创建图像数据集?

delphi Ado更新在2条记录之间插入

python - 无法在 DataFrame 中添加列名称

python - 从 Pandas 数据框中消除特定日期的最快方法

r - 在工具提示中显示多个额外变量

r - 对象错误[[名称,精确 = TRUE]] : subscript out of bounds