R tips: Use read.table instead of strsplit to split a text column into multiple columns


29 May 2009

Someone on the R-help mailing list had a data frame with a column containing IP addresses in quad-dot format (e.g. He wanted to sort by this column and I proposed a solution involving strsplit. But Peter Dalgaard comes up with a much nicer method using read.table on a textConnection object:

> a <- data.frame(cbind(color=c("yellow","red","blue","red"),
> con <- textConnection(as.character(a$ip))
> o <- do.call(order,read.table(con, sep="."))
> close(con)
> a[o,]
   color status            ip
3   blue    yes
2    red    yes
4    red     no
1 yellow     no

That is very, very neat! Thank you Peter.