Last active
August 15, 2017 10:44
-
-
Save arcaravaggi/38d9739380a08464e990427ba5222356 to your computer and use it in GitHub Desktop.
Arrange columns of dataframe by position
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##arrange df vars by position | |
# from https://stackoverflow.com/questions/5620885/how-does-one-reorder-columns-in-a-data-frame | |
##'vars' must be a named vector, e.g. c("var.name"=1) | |
# e.g. | |
# table <- data.frame(Time=c(1,2), In=c(2,3), Out=c(3,4), Files=c(4,5)) | |
# arrange.vars(table, c("Out"=2)) | |
# arrange.vars(table, c("Out"=2, "Files"=1, "Time"=4)) | |
arrange.vars <- function(data, vars){ | |
##stop if not a data.frame (but should work for matrices as well) | |
stopifnot(is.data.frame(data)) | |
##sort out inputs | |
data.nms <- names(data) | |
var.nr <- length(data.nms) | |
var.nms <- names(vars) | |
var.pos <- vars | |
##sanity checks | |
stopifnot( !any(duplicated(var.nms)), | |
!any(duplicated(var.pos)) ) | |
stopifnot( is.character(var.nms), | |
is.numeric(var.pos) ) | |
stopifnot( all(var.nms %in% data.nms) ) | |
stopifnot( all(var.pos > 0), | |
all(var.pos <= var.nr) ) | |
##prepare output | |
out.vec <- character(var.nr) | |
out.vec[var.pos] <- var.nms | |
out.vec[-var.pos] <- data.nms[ !(data.nms %in% var.nms) ] | |
stopifnot( length(out.vec)==var.nr ) | |
##re-arrange vars by position | |
data <- data[ , out.vec] | |
return(data) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment