[R] IP-Address

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Fri May 29 11:44:15 CEST 2009


Peter Dalgaard wrote:
> Allan Engelhardt wrote:
>   
>> IP addresses are very (very!) difficult to parse and sort correctly
>> because there are all sorts of supported formats.  Try to use something
>> like PostgreSQL instead: it is already implemented there.  But if you
>> are sure all your data is of the n.n.n.n form, then something along the
>> lines of the following should basically work (I have chosen some more
>> interesting IP addresses for this):
>>
>>
>> a <- data.frame(cbind(id=c(138,138,138,138),
>>                      rank=c(29746,29746,29746,29746),
>>                      color=c("yellow","red","blue","red"),
>>                      status=c("no","yes","yes","no"),
>>                     
>> ip=c("162.131.58.26","2.131.58.16","2.2.58.10","162.131.58.17")))
>> a
>> #    id  rank  color status            ip
>> # 1 138 29746 yellow     no 162.131.58.26
>> # 2 138 29746    red    yes   2.131.58.16
>> # 3 138 29746   blue    yes     2.2.58.10
>> # 4 138 29746    red     no 162.131.58.17
>> x <- matrix(unlist(lapply(strsplit(as.character(a$ip), ".", fixed=TRUE),
>> as.integer)),
>>            ncol=4, byrow=TRUE)
>> a[order(x[,1],x[,2],x[,3],x[,4]),]
>> #    id  rank  color status            ip
>> # 3 138 29746   blue    yes     2.2.58.10
>> # 2 138 29746    red    yes   2.131.58.16
>> # 4 138 29746    red     no 162.131.58.17
>> # 1 138 29746 yellow     no 162.131.58.26
>>
>>
>> Getting rid of the conversions including the matrix(unlist) combo is
>> left as an exercise (it's too hot here....)
>>     
>
> Here's one way:
>
> con <- textConnection(as.character(a$ip))
> o <- do.call(order,read.table(con,sep="."))
> close(con)
> a[o,]
>
>   

here's another:

    library(gsubfn)
    a[order(gsubfn(
        '[0-9]+',
        ~ sprintf('%03d', as.integer(x)),
        as.character(a$ip))),]

vQ




More information about the R-help mailing list