I'm not sure I understand what you are doing below but to rearrange columns of
a data.frame you can just rearrange the indices. Is this what you mean?
A couple of examples:
(mydata <- data.frame(aa=as.character(c("a", "b", "c", "d", "e")), bb = 1:5))
(mydata <- mydata[,2:1])
df1 <- structure(list(site = c(1, 1, 4, 4, 1, 4), id = structure(c(1L,
2L, 2L, 3L, 1L, 2L), .Label = c("a", "b", "c"), class = "factor"),
cata = c(1, 1, 6, 1, 1, NA), catb = c(1, 2, 3, 4, 5, 6),
doga = c(3, 5, 3, 6, 4, 0), dogb = c(2, 4, 6, 8, 10, 12),
rata = c(NA, 9, 9, 8, 9, 8), ratb = c(1, 2, 3, 4, 5, 6),
bata = c(12, 42, NA, 45, 32, 54), batb = c(13, 15, 17, 19,
21, 23)), .Names = c("site", "id", "cata", "catb", "doga",
"dogb", "rata", "ratb", "bata", "batb"), row.names = c("aa",
"bb", "cc", "dd", "ee", "ff"), class = "data.frame")
df1
(df1 <- df1[,rev(1:10)])
--- On Sat, 9/19/09, Santosh wrote:
> From: Santosh
> Subject: [R] Re-order columns
> To: r-help@r-project.org
> Received: Saturday, September 19, 2009, 11:25 AM
> Dear R'sians,
> Would really appreciate if you could suggest a more
> efficient way to order
> the columns of a dataset. The column names of the dataset
> contain indices
> separated by a period. Following are examples of my code
> and the dataset.
>
> oC <- function(tg=x2) {
> lth <-
> length(grep("T",names(tg)))
> thix <-
> match(paste("T",seq(lth),sep=""),names(tg))
> soi <-
> c(grep("O",names(tg),fixed=T),grep("S",names(tg),fixed=T))
> oi <-
> data.frame(t(data.frame(strsplit(names(tg)[soi],"\\."),stringsAsFactors=F)),stringsAsFactors=F)
> names(oi) <-
> c("par","ix1","ix2");row.names(oi) <- NULL
> oi$cnm <- sub("^\\s+((.*\\S)\\s+)?$",
> "\\2", paste("
> ",paste(oi$par,oi$ix1,oi$ix2," ",sep="."),sep=""))
> oi1 <-
> oi[order(oi$par,as.integer(oi$ix1),as.integer(oi$ix2)),]
> return(list(oi1=oi1,thix=thix))
> }
>
> x1 <- c("TABLE NO. 1: Gold" ,
> " R T2
> T1
> O.4.1.
> O.3.1.
> S.1.1. " ,
> " 0
> 3.68000E+01 1.41000E+03 4.94000E+03
> 2.33000E+01
> 4.9E+01",
> " 43
> 3.77870E+01 2.46260E+03 4.44227E+03
> 2.31390E+01
> 4.84272E+01",
> " -1
> 3.67870E+01 1.46260E+03 4.44227E+03
> 2.31390E+01
> 4.84271E+01")
> x2 <-
> read.table(textConnection(x1),as.is=T,head=T,skip=1)
> x3 <- oC(x2)
> pcols <- c(names(x2)[x3$thix],x3$oi1$cnm)
> x4 <-
> x2[,match(c(setdiff(names(x2),pcols),pcols),names(x2))]
>
> Thanks a TON
>
> Santosh
>
> [[alternative HTML version deleted]]
>
> __
> R-help@r-project.org
> mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained,
> reproducible code.
>
__
Get a
__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.