You can use sprintf to format partitions. For example, for a given numeric value of a you can do the following:
b <- sprintf("%.3d", a)
So, for the IP address, try this function:
printPadded <- function(x){ retStr = paste(sprintf("%.3d",unlist(lapply(strsplit(x,"\\.", perl = TRUE), as.numeric))), collapse = ".") return(retStr) }
Here are two examples:
> printPadded("1.2.3.4") [1] "001.002.003.004" > lapply(c("1.2.3.4","5.67.100.9"), printPadded) [[1]] [1] "001.002.003.004" [[2]] [1] "005.067.100.009"
To move in the other direction, we can remove the leading zeros using gsub for shared values ββin the printPadded function. For my money, I would recommend not removing leading zeros. It is not necessary to remove zeros (or fill them), but fixed-width formats are easier to read and sort (i.e., for those sorting functions that are lexicographic). A.
Update 1: just a hint about speed: if you are dealing with a large number of IP addresses and really want to speed it up, you can look at multi-core methods like mclapply . The plyr package plyr also useful, and ddply() as one option. They also support parallel servers via .parallel = TRUE . However, several million IP addresses should not be very time consuming even on a single core.
source share