Skip to content
Prev 181800 / 398503 Next

IP-Address

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....)

Allan.
edwin Sendjaja wrote: