[This article was first published on Exegetic Analytics » R, 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.
Suppose you have a data frame with a number of columns.
> names(trading) [1] "OpenDate" "CloseDate" "Symbol" "Action" "Lots" "SL" "TP" "OpenPrice" [9] "ClosePrice" "Commission" "Swap" "Pips" "Profit" "Gain" "Duration" "Trader" [17] "System"
You want to put the Trader and System columns first but you also want to do this in a flexible way. One approach would be to specify column numbers.
> trading = trading[, c(16:17, 1:15)] > names(trading) [1] "Trader" "System" "OpenDate" "CloseDate" "Symbol" "Action" "Lots" "SL" [9] "TP" "OpenPrice" "ClosePrice" "Commission" "Swap" "Pips" "Profit" "Gain" [17] "Duration"
This does the job but it’s not very flexible. After all, the number of columns might change. Rather do it by specifying column names.
> refcols <- c("Trader", "System") > # > trading <- trading[, c(refcols, setdiff(names(trading), refcols))] > names(trading) [1] "Trader" "System" "OpenDate" "CloseDate" "Symbol" "Action" "Lots" "SL" [9] "TP" "OpenPrice" "ClosePrice" "Commission" "Swap" "Pips" "Profit" "Gain" [17] "Duration"
The post R Recipe: Reordering Columns in a Flexible Way appeared first on Exegetic Analytics.
To leave a comment for the author, please follow the link and comment on their blog: Exegetic Analytics » R.
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.