R tips: Use read.table instead of strsplit to split a text column into multiple columns
[This article was first published on CYBAEA Data and Analysis, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Someone on the R-help mailing list had a data frame with a column containing IP addresses in quad-dot format (e.g. 1.10.100.200). 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"), status=c("no","yes","yes","no"), ip=c("162.131.58.26","2.131.58.16","2.2.58.10","162.131.58.17"))) > 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.2.58.10 2 red yes 2.131.58.16 4 red no 162.131.58.17 1 yellow no 162.131.58.26
That is very, very neat! Thank you Peter.
To leave a comment for the author, please follow the link and comment on their blog: CYBAEA Data and Analysis.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.