簡體   English   中英

R生成IP編號序列

[英]R Generate sequence of IP numbers

從...開始:

   OrigID  IP1              IP2
        1  111.111.111.250  111.111.112.005

所需的輸出:

   OrigId  IP1              IP2              IP
        1  111.111.111.250  111.111.112.005  111.111.111.250
        1  111.111.111.250  111.111.112.005  111.111.111.251
        1  111.111.111.250  111.111.112.005  111.111.111.252
        1  111.111.111.250  111.111.112.005  111.111.111.253
        1  111.111.111.250  111.111.112.005  111.111.111.254
        1  111.111.111.250  111.111.112.005  111.111.111.255
        1  111.111.111.250  111.111.112.005  111.111.112.001
        1  111.111.111.250  111.111.112.005  111.111.112.002
        1  111.111.111.250  111.111.112.005  111.111.112.003
        1  111.111.111.250  111.111.112.005  111.111.112.004
        1  111.111.111.250  111.111.112.005  111.111.112.005

基本上,生成從IP1IP2IP列表。 它不必位於同一數據框中,但是為了簡潔起見,此處以這種方式顯示。

iptools庫可以在這里提供幫助。 例如您的輸入數據

dd <- read.table(text=" OrigID  IP1              IP2
1  111.111.111.250  111.111.113.005", header=T, stringsAsFactors=FALSE)

我們可以編寫一個輔助函數

library(iptools)
ip_range <- function(start, end) {
  numeric_to_ip(ip_to_numeric(start):ip_to_numeric(end))
}

然后可以使用它來擴展行,這里使用dplyr

library(dplyr)    
dd %>% rowwise() %>% do({data.frame(., IP=ip_range(.$IP1, .$IP2))})

要得到

   OrigID IP1             IP2             IP             
 *  <int> <fct>           <fct>           <fct>          
 1      1 111.111.111.250 111.111.113.005 111.111.111.250
 2      1 111.111.111.250 111.111.113.005 111.111.111.251
 3      1 111.111.111.250 111.111.113.005 111.111.111.252
 4      1 111.111.111.250 111.111.113.005 111.111.111.253
 5      1 111.111.111.250 111.111.113.005 111.111.111.254
 6      1 111.111.111.250 111.111.113.005 111.111.111.255
 7      1 111.111.111.250 111.111.113.005 111.111.112.0  
 8      1 111.111.111.250 111.111.113.005 111.111.112.1  
 9      1 111.111.111.250 111.111.113.005 111.111.112.2  
10      1 111.111.111.250 111.111.113.005 111.111.112.3  
# ... with 258 more rows

如果您確實想使用前導零進行格式化,則可以編寫格式化程序。 例如在基數R中

format_ip <- function(x) {
  sapply(lapply(lapply(strsplit(x, ".", fixed=TRUE), as.numeric), function(x) sprintf("%03d", x)), paste0, collapse=".")
}

或使用purrr更具可讀性

library(purrr)
format_ip <- function(x) {
  x %>% strsplit(".", fixed=TRUE) %>% 
    map(~sprintf("%03d", as.numeric(.))) %>% 
    map_chr(paste0, collapse=".")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM